I. Overview
What is threadlocal? In fact, threadlocal is not a local implementation version of a thread, it is not a thread, but threadlocalvariable (thread local variable ). It may be more appropriate to name it threadlocalvar. Threadlocal provides a copy of the variable value for every thread that uses the variable. It is a special thread binding mechanism in Java, so that each thread can change its own copy independently without conflict with the copies of other threads.
From the thread perspective, each thread maintains an implicit reference to its local variable copy, as long as the thread is active and the threadlocal instance is accessible. After the thread disappears, all copies of the local instance of the thread will be garbage collected (unless there are other references to these copies ).
Data accessed through threadlocal is always related to the current thread. That is to say, JVM binds a private local instance access space for each running thread, this provides an isolation mechanism for concurrent access problems that often occur in multi-threaded environments.
How does threadlocal maintain copies of variables for each thread? In fact, the implementation idea is very simple. There is a map in the threadlocal class, which is used to store copies of the variables of each thread.
To sum up, for multi-threaded resource sharing, the synchronization mechanism adopts the "Time for space" approach, while threadlocal adopts the "space for Time" approach. The former provides only one copy of the variable, allowing different threads to queue for access, while the latter provides a copy of the variable for each thread. Therefore, the former can be accessed simultaneously without affecting each other.
Ii. API description
This class provides thread local variables. These variables are different from their common counterparts, because each thread accessing a variable (through its get or set method) has its own local variable, which is independent of the initialization copy of the variable. Threadlocal instances are usually private static fields in the class. They want to associate the state with a thread (for example, user ID or transaction ID.
For example, in the following class, the Private Static threadlocal instance (serialnum) is the static serialnum that calls the class. each thread of the get () method maintains a "Serial Number", which returns the serial number of the current thread. (The serial number of the thread is allocated when serialnum. Get () is called for the first time and will not be changed in subsequent calls .)
Threadlocal ()
Create a local variable of the thread.
T get ()
Returns the value in the current thread copy of the local variable of this thread. If this is the first time the thread calls this method, it is created and initialized.
Protected t initialvalue ()
Returns the initial value of the current thread for the local variable of this thread. This method can be called at most once each time the thread is accessed to obtain the local variable of each thread, that is, the first time the thread uses the get () method to access the variable. If the thread calls the Set (t) method before the get method, the initialvalue method is not called in the thread.
If this implementation only returns NULL, if the programmer wants to initialize a local variable of the thread to a value other than null, the programmer must create a subclass for threadlocal and override this method. Typically, anonymous internal classes are used. The typical Implementation of initialvalue calls an appropriate constructor and returns the newly constructed object.
Void remove ()
Remove the local variable value of this thread. This may help reduce the need to store local variables in the thread. If you access the local variable of this thread again, it will own its initialvalue by default.
Void set (T value)
Set the value in the current thread copy of the local variable of this thread to the specified value. Many applications do not need this function. They only rely on the initialvalue () method to set the value of the local variable of the thread.
In programs, the initialvalue method is generally rewritten to give a specific initial value.
Iii. Typical instances
1. hiberante's session tool class hibernateutil
This class is the hibernateutil class in the hibernate official documentation for session management.
Public class hibernateutil {<br/> Private Static log = logfactory. getlog (hibernateutil. class); <br/> Private Static final sessionfactory; // define sessionfactory </P> <p> static {<br/> try {<br/> // use the default configuration file hibernate. cfg. XML creates sessionfactory <br/> sessionfactory = new configuration (). configure (). buildsessionfactory (); <br/>} catch (throwable ex) {<br/> log. error ("failed to initialize sessionfactory! ", Ex); <br/> throw new exceptionininitializererror (Ex); <br/>}< br/> // create a thread local variable session, used to save the hibernate session <br/> Public static final threadlocal session = new threadlocal (); </P> <p>/** <br/> * obtain the session in the current thread <br/> * @ return session <br/> * @ throws hibernateexception <br/> */<br/> Public static session currentsession () throws hibernateexception {<br/> session S = (Session) session. get (); <Br/> // if the session has not been opened, a new session is created. <br/> If (S = NULL) {<br/> S = sessionfactory. opensession (); <br/> session. set (s); // Save the new session to the local variable of the thread <br/>}< br/> return S; <br/>}</P> <p> Public static void closesession () throws hibernateexception {<br/> // gets the local variable of the thread, and forcibly converted to the session type <br/> session S = (Session) session. get (); <br/> session. set (null); <br/> If (s! = NULL) <br/> S. Close (); <br/>}< br/>}
In this class, because the initialvalue () method of threadlocal is not overwritten, the initial value of the thread local variable session created for the first time is null. When currentsession () is called for the first time, the get () method of the local variable of the thread is also null. Therefore, the session is determined. If it is null, a new session is created and saved to the local variable Session of the thread. This step is critical, this is also the reason why the Session of the object created by "public static final threadlocal session = new threadlocal ()" can be forcibly converted to the hibernate session object.
2. Another instance
Create a bean and set bean attributes through different thread objects to ensure the independence of bean objects in various threads.
Public class student {<br/> private int age = 0; // age </P> <p> Public int getage () {<br/> return this. age; <br/>}</P> <p> Public void setage (INT age) {<br/> This. age = age; <br/>}< br/> public class threadlocaldemo implements runnable {<br/> // create the thread local variable studentlocal, you will find the student object to save <br/> private final static threadlocal studentlocal = new threadlocal (); </P> <p> Public static void main (St Ring [] AGRs) {<br/> threadlocaldemo TD = new threadlocaldemo (); <br/> thread T1 = new thread (TD, ""); <br/> thread t2 = new thread (TD, "B"); <br/> t1.start (); <br/> t2.start (); <br/>}</P> <p> Public void run () {<br/> accessstudent (); <br/>}</P> <p>/** <br/> * example business method, used to test <br/> */<br/> Public void accessstudent () {<br/> // obtain the name of the current thread <br/> string currentthreadname = thread. currentthread (). getna Me (); <br/> system. Out. println (currentthreadname + "is running! "); <Br/> // generate a random number and print it <br/> random = new random (); <br/> int age = random. nextint (100); <br/> system. out. println ("Thread" + currentthreadname + "set age to:" + age); <br/> // gets a student object, and insert the random number age into the object property. <br/> Student = getstudent (); // In fact, there is no thread security problem in direct new student, the test results are the same. Local variables do not have thread security issues. <Br/> student. setage (AGE); <br/> system. out. println ("Thread" + currentthreadname + "first read age is:" + student. getage (); <br/> try {<br/> thread. sleep (500); <br/>}< br/> catch (interruptedexception ex) {<br/> ex. printstacktrace (); <br/>}< br/> system. out. println ("Thread" + currentthreadname + "second read age is:" + student. getage (); <br/>}</P> <p> protected student getstudent () {<br/> // obtain the local thread variable and forcibly convert it to the student type <br/> Student = (student) studentlocal. get (); <br/> // when the thread executes this method for the first time, studentlocal. get () must be null <br/> If (student = NULL) {<br/> // create a student object, and save it to the local thread variable studentlocal <br/> Student = new student (); <br/> studentlocal. set (student); <br/>}< br/> return student; <br/>}< br/>
Running result:
A is running!
Thread a set age to: 76
B is running!
Thread B set age to: 27
Thread a first read age is: 76
Thread B first read age is: 27
Thread a second read age is: 76
Thread B second read age is: 27
We can see that the values of the age threads A and B are exactly the same at different times. This program uses threadlocal to achieve multi-thread concurrency, while ensuring data security. (Threadlocal is not required here. The same is true for direct new student () tests. Local variables do not have thread security issues .)
Iv. Summary
Threadlocal is used to solve data inconsistency caused by concurrency in multiple threads. Threadlocal provides a copy of the data concurrently accessed by each thread and runs the business by accessing the copy. This results in memory consumption, which greatly reduces the performance consumption caused by thread synchronization, it also reduces the complexity of thread concurrency control.
Threadlocal cannot use the atomic type, but can only use the object type. Threadlocal is much easier to use than synchronized.
Both threadlocal and synchonized are used to solve multi-thread concurrent access. However, threadlocal is essentially different from synchronized. Synchronized uses the lock mechanism to allow a variable or code block to be accessed by only one thread at a time. Threadlocal provides a copy of the variable for each thread, so that each thread does not access the same object at a certain time, thus isolating multiple threads from sharing data. Synchronized, on the contrary, is used to obtain data sharing when multiple threads communicate.
Synchronized is used for data sharing between threads, while threadlocal is used for data isolation between threads.
Of course, threadlocal cannot replace synchronized. They process different problem domains. Synchronized is used to implement synchronization mechanism, which is more complex than threadlocal.
5. General steps for using threadlocal
1. Create a threadlocal object threadxxx in a multi-threaded class (such as threaddemo class) to save the xxx object to be isolated and processed between threads.
2. In the threaddemo class, create a method getxxx () to obtain the data to be isolated, and Judge in the method. If the threadlocal object is null, it should be new () an object that isolates the access type and forcibly converts it to the type to be applied. You can also set it by using the threadlocal set method at the beginning.
3. In the run () method of the threaddemo class, use the getxxx () method to obtain the data to be operated. This ensures that each thread corresponds to a data object, this object is operated at any time.