The threadlocal class provides a place for each thread to store local variables.
Essentially, each currently running thread holds a map. The threadlocal class encapsulates access to this map. Therefore, you can put a newly generated object into this map through threadlocal in the thread, this ensures that the thread is only available in the thread each time it gets from the threadlocal object, that is, the object in the map, and will not be accessed by other threads.
The article "threadlocal design and use" mentions that threadlocal is not implemented like the following;
Public class threadlocal
{
Private map values = collections. synchronizedmap (New hashmap ());
Public object get ()
{
Thread curthread = thread. currentthread ();
Object o = values. Get (curthread );
If (O = NULL &&! Values. containskey (curthread ))
{
O = initialvalue ();
Values. Put (curthread, O );
}
Return O;
}
Public void set (Object newvalue)
{
Values. Put (thread. currentthread (), newvalue );
}
Public object initialvalue ()
{
Return NULL;
}
}
In fact, this map is not maintained by threadlocal, but every thread. The advantage of doing so is that every time the thread dies, all the objects referenced in the map will be collected together with the thread's death by the garbage collector (of course, the premise is that it is not referenced elsewhere)
The key of this map is a weak reference to the threadlocal object. to discard the threadlocal object, the garbage collector will ignore the reference of this key and clear the threadlocal object.
As recommended by Java Doc, threadlocal is declared as public static.
Method Summary
T get ()
Returns the value of the local variable in the current thread copy.
Protected t initialvalue ()
Returns the "Initial Value" of the current thread for the local variable of this thread ".
Void remove ()
Remove the value of the current thread of the local variable of this thread.
Void set (T value)
Set the value in the current thread copy of the local variable of this thread to the specified value.