Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

when are static ThreadLocal variables intialized

 
Yan Zhou
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is from ThreadLocal's JavaDoc.

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();
}
}
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yan,

1. http://java.sun.com/developer/JDCTechTips/2003/tt1208.html#2
2. http://www-106.ibm.com/developerworks/java/library/j-threads3.html

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..

Though I found IBM's article with more insights.

Thanks
Maulin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic