Reputation: 2136
Below are the example of creating the Thread Local variable
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
};
And Also Second way to use Thread Local
public class MyThreadLocal {
public static final ThreadLocal userThreadLocal = new ThreadLocal();
public static void set(Context user) {
userThreadLocal.set(user);
}
public static void unset() {
userThreadLocal.remove();
}
public static Context get() {
return userThreadLocal.get();
}
}
Now,The below line create a thread local variable and it is static.
public static final ThreadLocal userThreadLocal = new ThreadLocal();
Static variables are initialized whenever class is loaded in JVM. That means one object is created When the class loads.
**Question: *When different Thread calls Set or get on ThreadLocal variable how is the copy of threadlocal object is passed to the thread?*How each Thread gets its own object? If one object is created when class is loaded ,then how is this happening?**
Upvotes: 2
Views: 6184
Reputation: 262504
This is actually part of the implementation of Thread.
In principle, you can think of each Thread instance having a Map, where the ThreadLocal object instance (of which there is only one) is the key and the value associated to it is the value.
The static instance of ThreadLocal does not hold the value at all, it is just a marker for the Thread to look it up again (the Thread stores the value).
So
userThreadLocal.get();
is something like
currentThread.privateMapOfThreadLocalValues.get(userThreadLocal);
Upvotes: 4
Reputation: 21883
I think the answer is clearly described in the documentation for ThreadLocal
To summarize I quote
This 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).
and
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).
Hope this clarifies.
Upvotes: 1