What is threadlocal? In fact, Threadlocal is not a local implementation version of a thread, it is not a threaded, but a threadlocalvariable (thread local variable). Perhaps it would be more appropriate to name it Threadlocalvar. The thread local variable (ThreadLocal) function is very simple, that is, for each thread that uses the variable to provide a copy of the value of a variable, is a special thread binding mechanism in Java, is that each thread can independently change its own copy, and does not conflict with the copy of other threads. From a thread's point of view, each thread maintains an implicit reference to a copy of its thread's local variables, as long as the thread is active and the ThreadLocal instance is accessible, and all copies of its thread's local instance are garbage collected after the threads have disappeared (unless there are other references to those replicas). The data accessed through threadlocal is always related to the current thread, that is, the JVM binds the private local instance access space for each running thread, thus providing an isolation mechanism for concurrent access problems that often occur in multithreaded environments. How does threadlocal maintain a copy of a variable for each thread? In fact, the idea of implementation is simple, there is a map in the Threadlocal class that stores a copy of each thread's variable. To sum up, for the problem of multi-thread resource sharing, the synchronization mechanism adopts the way of "time-changing Space", and threadlocal adopts the way of "changing time by Space". The former provides only one copy of the variable, allowing different threads to queue access, and the latter provides a variable for each thread, so it can be accessed at the same time without affecting each other.
First of all, the value of threadlocal stored in the thread is shared, mutually exclusive between threads, mainly used in the thread to share some data, to avoid passing parameters , so that after processing, can gracefully solve some practical problems, For example, hibernate in the Opensessioninview, is to use threadlocal Save Session object, and we often use threadlocal store connection, code such as:
1 /**2 * Database connection management class3 * @authorCool4 *5 */6 Public classConnectionManager {7 8 /**in-thread shared connection,threadlocal are generally global and support generics*/9 Private StaticThreadlocal<connection> ThreadLocal =NewThreadlocal<connection>();Ten One Public StaticConnection getcurrconnection () { A //gets the connection shared within the current thread -Connection conn =threadlocal.get (); - Try { the //determine if the connection is available - if(conn = =NULL||conn.isclosed ()) { - //Create a new connection assignment to Conn (slightly) - //Save Connection + Threadlocal.set (conn); - } +}Catch(SQLException e) { A //Exception Handling at } - returnConn; - } - - /** - * Close the current database connection in */ - Public Static voidClose () { to //gets the connection shared within the current thread +Connection conn =threadlocal.get (); - Try { the //determine if it has been closed * if(Conn! =NULL&&!conn.isclosed ()) { $ //Close ResourcePanax Notoginseng conn.close (); - //Remove Connection the Threadlocal.remove (); +conn =NULL; A } the}Catch(SQLException e) { + //Exception Handling - } $ } $}
The benefits of such treatment:
- Unified management Connection;
- No need to display the connection, the code is more elegant;
- Reduce coupling.
Threadlocal has four methods, respectively:
InitialValue
InitialValue ()
-
Returns the initial value of the current thread for this thread's local variables. This method is called at most once per access thread to obtain a local variable for each of the threads, that is,
get() when the thread first accesses the variable using the method. If the thread calls the method before the get method set(T) , the initialvalue method will not be called again in threads.
The implementation only returns null, and if the programmer wants to initialize a thread-local variable to a value other than null , you must create a subclass for ThreadLocal and override this method. Typically, anonymous inner classes are used. A typical implementation of InitialValue invokes an appropriate construction method and returns the newly constructed object.
-
-
Return:
-
returns the initial value of the local variable for this thread
Get
Get ()
-
Returns the value in the current thread copy of this thread's local variable. If this is the first time a thread calls the method, the replica is created and initialized.
-
-
Return:
The
-
value of the current thread for this thread's local variables
Set
Set (T value)
-
Sets the value in the current thread copy of this thread's local variable to the specified value. Many applications do not require this functionality, they rely only on
initialValue() methods to set the value of thread-local variables.
-
-
Parameters:
-
value -Stores the value in the current thread copy of this thread's local variable.
Remove
Remove ()
-
removes the value of this thread's local variable. This may help reduce the storage requirements for thread-local variables. If you access this thread's local variable again, by default it will have its initialvalue.
Many people have a certain misunderstanding of the threadlocal, saying that Threadlocal has a global map,set when executing map.put (Thread.CurrentThread (), value), get and remove also the same, But whether Sun's masters are so fulfilled, we can only see the source code.
Set Method:
1 /**2 * Sets the current thread's copy of this thread-local variable3 * to the specified value. Most subclasses'll has no need to4 * Override this method, relying solely on the {@link#initialValue}5 * method to set the values of Thread-locals.6 *7 * @paramValue the value to being stored in the current thread ' s copy of8 * this thread-local.9 */Ten Public voidset (T value) { One //gets the current thread object AThread T =Thread.CurrentThread (); - //gets the current thread local variable map -Threadlocalmap map =Getmap (t); the //map is not empty - if(Map! =NULL) - //stored value -Map.set ( This, value); + Else - //Create a current thread local variable map + Createmap (t, value); A } at - /** - * Get The map associated with a ThreadLocal. Overridden in - * inheritablethreadlocal. - * - * @paramt the current thread in * @returnThe map - */ to threadlocalmap Getmap (Thread t) { + //gets the local variable map for the current thread - returnt.threadlocals; the}
Note here that there is a map in threadlocal, but this map is not the map we normally use, but Threadlocalmap,threadlocalmap is an internal class of threadlocal that is not used externally. When Threadlocal is used, the first is to get to the current thread object, and then get to the current thread local variable map, and finally put the currently used threadlocal and incoming values into the map, that is, the value stored in Threadlocalmap is [ Threadlocal object, stored value], the advantage is that each thread corresponds to a map of a local variable, so a thread can have multiple thread local variables .
Get method:
1 /**2 * Returns The value in the current thread ' s copy of this3 * thread-local variable. If the variable have no value for the4 * Current thread, it was first initialized to the value returned5 * by an invocation of the {@link#initialValue} method.6 *7 * @returnThe current thread ' s value of this thread-local8 */9 PublicT Get () {TenThread T =Thread.CurrentThread (); OneThreadlocalmap map =Getmap (t); A if(Map! =NULL) { -Threadlocalmap.entry e = Map.getentry ( This); - if(E! =NULL) the return(T) e.value; - } - //if the value is null, the initial value is returned - returnSetinitialvalue (); +}
With the analysis of the previous set method, the Get method is also the same, it should be explained that if there is no set operation, then the value obtained from Threadlocalmap is null, then the GET method will return the initial value, that is, call the InitialValue () method, This method returns null by default in Threadlocal. When we need to get a value for the first get, we can inherit threadlocal and overwrite the InitialValue () method.
Finish
This article from: Gao | Coder, original address: http://blog.csdn.net/ghsau/article/details/15732053
Java Thread Local Variables