Spring Learning 11-spring using threadlocal to solve thread safety problems

Source: Internet
Author: User

What is threadlocal?
As early as the version of JDK 1.2, Java.lang.threadlocal,threadlocal provides a new way to solve the concurrency problem of multi-threaded threads. Using this tool class, you can write beautiful multithreaded programs very concisely.
Threadlocal is easy to words too literally, assuming it is a "local thread". In fact, threadlocal is not a thread, but a local variable of thread, perhaps naming it as threadlocalvariable is easier to understand.
When you use threadlocal to maintain variables, Threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy without affecting the copy of the other thread.
From the thread's point of view, the target variable is like a thread's local variable, which is the meaning of the "local" in the class name.
Thread-local variables are not a new Java invention, and many languages (such as IBM IBM XL FORTRAN) provide thread-local variables at the syntactic level. There is no language-level support in Java, but rather a disguised way to provide support through the Threadlocal class.
Therefore, the code to write thread-local variables in Java is relatively clumsy, resulting in thread-local variables not being well-popularized in Java developers.
interface method for Threadlocal
Threadlocal class interface is very simple, there are only 4 methods, let us first look at:
void set (Object value) sets the value of the thread local variable for the current thread.
Public Object Get () This method returns the thread local variable that corresponds to the current thread.
The public void Remove () Removes the value of the current thread local variable to reduce memory usage, which is a new method of JDK 5.0. It is important to note that when the thread ends, the local variables of the thread that should be used are automatically garbage collected, so it is not necessary to explicitly call the method to clear the thread's local variables, but it can speed up the memory reclamation.
Protected Object InitialValue () returns the initial value of the thread's local variable, which is a protected method, apparently designed to allow subclasses to overwrite. This method is a deferred call method that executes only when the thread calls get () or set (Object) for the 1th time, and executes only 1 times. The default implementation in Threadlocal returns a null directly.
It is worth mentioning that, in JDK5.0, Threadlocal already supports generics, and the class name of the class has become threadlocal<t>. The API methods are also adjusted accordingly, and the new version of the API method is void set (t value), t get (), and T InitialValue ().
How does threadlocal maintain a copy of a variable for each thread? The idea is simple: there is a map in the Threadlocal class that stores a copy of the variable for each thread, the key for the element in the map is the thread object, and the value corresponds to the variable copy of the thread. We can provide a simple implementation version by ourselves:
Code Listing 1

Java code
simplethreadlocal Public classsimplethreadlocal {PrivateMap ValueMap = Collections.synchronizedmap (NewHashMap ());  Public voidset (Object newvalue) {valuemap.put (Thread.CurrentThread (), newvalue);//The ① key is a thread object, and the value is a copy of the variable for this thread}    PublicObject Get () {Thread CurrentThread=Thread.CurrentThread (); Object o= Valuemap.get (CurrentThread);//② returns the variable corresponding to this threadif(O = =NULL&&!valuemap.containskey (CurrentThread)) {//③ If it does not exist in the map, put it in the map to save it. o =InitialValue ();   Valuemap.put (CurrentThread, O); }   returno; }    Public voidRemove () {Valuemap.remove (Thread.CurrentThread ()); }    PublicObject InitialValue () {return NULL; }   }   

Although the code listing 9?3 this threadlocal implementation version seems naïve, it is similar to the Threadlocal class provided by the JDK in the implementation.
A theadlocal instance
Below, we have a specific example to understand the specific use of threadlocal.
Code Listing 2

Java code
SequenceNumber PackageCom.baobaotao.basic;  Public classSequenceNumber {//① Specifies the initial value by overwriting the Threadlocal InitialValue () method with an anonymous inner classPrivate StaticThreadlocal<integer> SeqNum =NewThreadlocal<integer>(){    PublicInteger InitialValue () {return0;   }   }; //② getting the next sequence value Public intGetnextnum () {Seqnum.set (Seqnum.get ()+1); returnSeqnum.get (); }    Public Static voidMain (string[] args) {sequencenumber sn=NewSequenceNumber (); //③ 3 threads sharing sn, each generating serial numbertestclient T1 =Newtestclient (SN); TestClient T2=Newtestclient (SN); testclient T3=Newtestclient (SN);   T1.start ();   T2.start ();   T3.start (); }   Private Static classTestClientextendsThread {PrivateSequenceNumber SN;  Publictestclient (SequenceNumber sn) { This. SN =SN; }    Public voidrun () { for(inti = 0; I < 3; i++) {//④ 3 sequence values per threadSystem.out.println ("thread[" +thread.currentthread (). GetName () + "] sn[" +sn.getnextnum () + "]"); }   }   }   }   

In general, we define the subclass of threadlocal by means of an anonymous inner class, providing the initial variable value, as shown in the example ①. TestClient threads produce a set of serial numbers, and at ③ we generate 3 testclient that share the same SequenceNumber instance. Run the above code and output the following results on the console:

Thread[thread-2] sn[1] Thread[thread-0] sn[1] Thread[thread-1] sn[1] Thread[thread-2] sn[2 ] Thread[thread-0] sn[2] Thread[thread-1] sn[2] Thread[thread-2] sn[3] Thread[thread -0] sn[3] Thread[thread


Examining the results of the output, we find that each thread produces a sequence number that shares the same SequenceNumber instance, but they do not interfere with each other, but instead produce separate serial numbers. This is because we provide a separate copy of each thread through threadlocal.
Comparison of thread synchronization mechanisms
What are the advantages of threadlocal compared to the thread synchronization mechanism? Both the threadlocal and thread synchronization mechanisms are designed to address the access violation of the same variable in multiple threads.
In the synchronization mechanism, the lock mechanism of the object guarantees that only one thread accesses the variable at the same time. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when to lock an object, when to release object locks and other complex problems, programming and writing is relatively difficult.
Threadlocal, however, solves multiple threads of concurrent access from another angle. Threadlocal provides a separate copy of the variable for each thread, isolating the access violation of multiple threads to the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects that can encapsulate unsafe variables into threadlocal when writing multithreaded code.
Because the threadlocal can hold any type of object, the Get () provided by the lower version of the JDK returns an object, which requires a type cast. But JDK 5.0 solves this problem with generics, and simplifies the use of threadlocal to some extent, and listing 9 2 uses the new threadlocal<t> version of JDK 5.0.
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.
Spring uses threadlocal to resolve thread safety issues
We know that in general, only stateless beans can be shared in a multithreaded environment, and in spring, most beans can be declared as singleton scopes. It is because spring uses a non-thread-safe state for some beans (such as Requestcontextholder, Transactionsynchronizationmanager, Localecontextholder, etc.) Threadlocal are processed to make them also a thread-safe state, because stateful beans can be shared across multiple threads.
The general Web application divides into the presentation layer, the service layer and the persistence layer three levels, writes the corresponding logic in the different layers, the lower layer through the interface to the upper layer open function calls. In general, all program calls from receiving requests to returning responses belong to one thread, as shown in 9?2:

Figure 1 The same thread through three layers
This allows you to store some non-thread-safe variables in threadlocal as needed, and all associated objects are referenced to the same variable in the calling thread of the same request response.
The following example can reflect spring's transformation of the stateful bean:
Code Listing 3

 Package com.spring; Import java.sql.Connection; Import java.sql.SQLException; Import java.sql.Statement;  Public class Topicdao {        private  Connection conn;          Public void throws sqlexception{                Statement stat=conn.createstatement ();            }        }

Because the conn at ① is a member variable, because the Addtopic () method is non-thread-safe, a new Topicdao instance (not singleton) must be created when it is used. The following uses Threadlocal to transform Conn, a non-thread-safe "state":
Code Listing 4

 Packagecom.spring;Importjava.sql.Connection;Importjava.sql.SQLException;Importjava.sql.Statement; Public classTopicDao1 {Private StaticThreadlocal<connection> connthreadlocal =NewThreadlocal<connection>(); Public StaticConnection getconnection () {if(Connthreadlocal.get () = =NULL) {Connection conn=connectionmanager.getconnection ();        Connthreadlocal.set (conn); returnConn; }Else{        returnConnthreadlocal.get (); }        } Public voidAddtopic ()throwsSQLException {Statement State=getconnection (). createstatement ();}}

When using Topicdao, different threads first determine if Connthreadlocal.get () is null, or NULL, indicating that the current thread does not have a corresponding connection object. At this point, a connection object is created and added to the local thread variable, and if it is not NULL, the current thread already has the connection object, which can be used directly. This ensures that different threads use thread-related Connection and do not use the Connection of other threads. Therefore, this topicdao can be done singleton share.
Of course, this example itself is very rough, put connection threadlocal directly in DAO can only do this DAO's multiple methods share connection without thread safety problem, but can not be shared with other DAO the same connection, To do the same transaction multiple DAO shares the same connection, you must use Threadlocal to save the connection in a common external class. But this example basically illustrates spring's approach to stateful thread security.
Summary
Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency.

Spring Learning 11-spring using threadlocal to solve thread safety problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.