views:

122

answers:

2

Hi, I was just wonderhing how some libraries can detect in which thread they run and "bind" something to it... for example the Mapped Diagnostic Context (MDC) of log4j or Context.enter() from Mozilla Rhino. How could i do that, just in case i'll stumble upon a case where i need this. ;-)

Have a nice day!

A: 

You mean :

Thread.currentThread();

maybe?

Savvas Dalkitsis
+7  A: 

You can have per-thread information using ThreadLocal variables. I don't know anything about the details of Rhino or log4j, but I imagine this is how they do it.

Example from the Javadoc that assigns a different serial number to each thread.

 public class SerialNum {
     // The next serial number to be assigned
     private static int nextSerialNum = 0;

     private static ThreadLocal serialNum = new ThreadLocal() {
         protected synchronized Object initialValue() {
             return new Integer(nextSerialNum++);
         }
     };

     public static int get() {
         return ((Integer) (serialNum.get())).intValue();
     }
 }
Zarkonnen
Just don't use the example in the current `ThreadLocal` API docs.
Tom Hawtin - tackline