Threadlocal implementation principle, and use instances to solve the problem of no session or session was closed in non-web projects of spring and hibernate. (2 )!

Source: Internet
Author: User

Comparison of thread synchronization mechanisms

What are the advantages of threadlocal over thread synchronization? Threadlocal and thread synchronization mechanisms are designed to solve the access conflict between the same variables in multiple threads.

In the synchronization mechanism, the object lock mechanism ensures that only one thread accesses the variable at a time. At this time, the variable is shared by multiple threads. The synchronization mechanism requires the program to carefully analyze when to read and write the variable, and when to lock an object, when to release the object lock and other complicated issues, it is relatively difficult to design and write the program.

Threadlocal solves multi-thread concurrent access from another perspective. Threadlocal provides an independent copy of variables for each thread, thus isolating multiple threads from access conflicts to Data. Because every thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides thread-safe shared objects. When writing multi-threaded code, you can encapsulate insecure variables into threadlocal.

Because threadlocal can hold any type of objects, get () provided by JDK of lower versions returns object objects and requires forced type conversion. However, JDK 5.0 solves this problem through generics and simplifies the use of threadlocal to a certain extent. In Code List 9 2, the new threadlocal version of JDK 5.0 is used.

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.

Spring uses threadlocal to solve thread security problems

We know that in general, only stateless beans can be shared in multi-threaded environments. In spring, most beans can be declared as Singleton scopes. This is because spring uses threadlocal to process non-thread security states in some beans (such as requestcontextholder, transactionsynchronizationmanager, and localecontextholder), making them thread-safe, because stateful beans can be shared in multiple threads.

Generally, web applications are divided into three layers: presentation layer, service layer, and persistence layer. The corresponding logic is written in different layers. The lower layer opens function calls through interfaces to the upper layer. In general, all program calls from receiving a request to returning a response belong to the same thread, as shown in figure 9:

Figure 1 three layers of a thread

In this way, you can store non-thread-safe variables as threadlocal as needed. In the call thread of the same request response, all associated Objects Reference the same variable.

The following example shows how spring modifies stateful beans:

Code List 3 topicdao: Non-thread security

Public class topicdao {</P> <p> private connection conn; ① A non-thread-safe variable </P> <p> Public void addtopic () {</P> <p> statement stat = Conn. createstatement (); ② reference a non-thread security variable </P> <p>... </P> <p >}< br/>

 

Import Java. SQL. connection; </P> <p> Import Java. SQL. statement; </P> <p> public class topicdao {</P> <p> ① use threadlocal to save the connection variable </P> <p> Private Static threadlocal <connection> connthreadlocal = new threadlocal <connection> (); </P> <p> Public static connection getconnection () {</P> <p> ② If connthreadlocal does not have the connection corresponding to this thread, create a new connection, </P> <p> and save it to the local variable of the thread. </P> <p> If (connthreadlocal. get () = NULL) {</P> <p> connection conn = connectionmanager. getconnection (); </P> <p> connthreadlocal. set (conn); </P> <p> return conn; </P> <p >}else {</P> <p> return connthreadlocal. get (); ③ directly return the local variable of the thread </P> <p >}</P> <p> Public void addtopic () {</P> <p> ④ obtain the connection corresponding to the thread from threadlocal </P> <p> statement stat = getconnection (). createstatement (); </P> <p >}</P> <p>

Because the conn at ① Is a member variable, because the addtopic () method is non-thread-safe, you must create a new topicdao instance (not Singleton) when using it ). The following uses threadlocal to transform the non-thread-safe state of Conn:

Code list 4 topicdao: thread security

When different threads use topicdao, determine connthreadlocal first. whether get () is null. If it is null, it indicates that the current thread has no corresponding connection object. In this case, create a connection object and add it to the local thread variable. If it is not null, it indicates that the current thread already has a connection object and can be used directly. This ensures that different threads Use thread-related connections instead of other threads. Therefore, this topicdao can be shared by Singleton.

Of course, this example is rough. Placing the threadlocal of connection directly on Dao can only achieve that thread security issues do not occur when multiple methods of the DaO share the connection, but it cannot share the same connection with other Dao. To share the same connection with multiple Dao in the same transaction, threadlocal must be used in a common external class to save the connection.

 

We often use currentsession () when using hibernate, while hibernat uses threadlocal as follows:

Public static final threadlocal session = new threadlocal (); <br/> Public static session currentsession () {<br/> session S = (Session) session. get (); <br/> // open a new session, if this session has none <br/> If (S = NULL) {<br/> S = sessionfactory. opensession (); <br/> session. set (s); <br/>}< br/> return s; <br/>}< br/>

1. Initialize a threadlocal object. threadlocal has three member Methods: Get (), set (), and initialvalue ().
If initialvalue is not initialized, initialvalue returns NULL.
3. Session get returns the corresponding internal thread variables based on the current thread, that is, the net. SF. hibernate. session (equivalent to each database connection ). it is insecure to share database links with multiple threads. Threadlocal ensures that each thread has its own S (database connection ).
5. If the thread is accessed for the first time, naturally, S (database connection) will be null and a session will be created, specifically Row 6.
6. Create a database connection instance s
7. Save the database connection s to threadlocal.
8. If the current thread has accessed the database, get () from the session to obtain the connection instance that the thread has obtained last time.

 

 

Summary

Threadlocal is a good idea to solve the thread security problem. It solves the conflict of variable concurrent access by providing an independent variable copy for each thread. In many cases, threadlocal is easier and more convenient than directly using synchronized synchronization mechanism to solve thread security problems, and the result program has higher concurrency.

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.