ThreadLocal - I

20 August 2008

If you want to have thread-local variables, then ThreadLocal is to be used.

The thread-local variables are different from normal ones because each thread that accesses a variable via its get or set method, has its own, independently initialized copy of the variable.

Typically, ThreadLocal instances are private static fields in classes that wish to associate state with a thread. Some examples can be a user ID Transaction ID, Student ID etc.

The example given below has private static ThreadLocal instance called serialNum. It maintains a “serial number” for each thread that invokes the class’s static SerialNum.get() method, which returns the current thread’s serial number. (A thread’s serial number is assigned the first time it invokes SerialNum.get(), and remains unchanged on subsequent calls.)

 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();
     }
 }

continued …

del.icio.us:ThreadLocal - I  digg:ThreadLocal - I  spurl:ThreadLocal - I  wists:ThreadLocal - I  simpy:ThreadLocal - I  newsvine:ThreadLocal - I  blinklist:ThreadLocal - I  furl:ThreadLocal - I  reddit:ThreadLocal - I  fark:ThreadLocal - I  blogmarks:ThreadLocal - I  Y!:ThreadLocal - I  smarking:ThreadLocal - I  magnolia:ThreadLocal - I  segnalo:ThreadLocal - I  gifttagging:ThreadLocal - I

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: ThreadLocal - I

Leave a Reply