All static variables are initialized when classes are loaded, before the main() even starts. I wonder whether static ThreadLocal variables are so, too.
I do not think that ThreadLocal variables would be initialized before threads are created, may be they are initialized when threads are created?
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(); } }
I think you are imagining ThreadLocal to be somehow "magic", but in fact it is a pure Java class. It has no native methods and no special hooks into the JVM. You can look at its source, in the JDK.
When the class, containing a static field that is a reference to a ThreadLocal, is loaded, that field is initialised.
In your example, the initialisation of the static field involves constructing an instance of ThreadLocal().
When you first use methods on your instance of ThreadLocal, in a particular thread, the ThreadLocal's value for that thread is initialised to whatever the initialValue() method returns.
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
These links should be good for help. I read it carefully and I got how it works. Also, at the end of the techtip article they recommend to look at LogRecord and Charset classes in the JDK API and I looked at their sources to see how they are using ThreadLocal..