Wednesday, September 8, 2010

Use of ThreadLocal class

ThreadLocal helps to maintain a separate copy of the value for each thread that use it, it is often used to prevent sharing in designs based on mutable Singletons or global variables.
Conceptually, you can think of a ThreadLocal as holding a Map that stores the thread specific values, but the real implementation is not this way, the read data actually stored in the Thread object itself.

In Thread class, there are two private variables:
ThreadLocal.Values localValues;
ThreadLocal.Values inheritableValues;

Here is how the real per-thread values are stored. (ThreadLocal.set()):

public void set(T value) {
Thread currentThread = Thread.currentThread();
Values values = values(currentThread);
if (values == null) {
values = initializeValues(currentThread);
}
values.put(this, value);
}

Values values(Thread current) {
return current.localValues;
}

Values initializeValues(Thread current) {
return current.localValues = new Values();
}

From the above code, we may see that ThreadLocal set values into Thread object's
localValues variable.When the thread terminates, the thread-specific values can be GCed.

For details please see:
crazybob.org: Hard Core Java: ThreadLocal


No comments:

Post a Comment