Thursday, July 10, 2008

ThreadLocal

ThreadLocal class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

For example, in the class below, the private static ThreadLocal instance (serialNum) 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();      }  }  

Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist).