wood burning stoves 2.0
The moose likes Java in General and the fly likes when are static ThreadLocal variables intialized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "when are static ThreadLocal variables intialized" Watch "when are static ThreadLocal variables intialized" New topic

when are static ThreadLocal variables intialized

Yan Zhou
Ranch Hand

Joined: Sep 02, 2003
Posts: 137
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

Joined: Oct 30, 2001
Posts: 1970
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.
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
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.

I agree. Here's the link: http://aspose.com/file-tools
subject: when are static ThreadLocal variables intialized
It's not a secret anymore!