Thread local change threadlocal-->spring transaction management

Source: Internet
Author: User
Tags memory usage sessions
We know that spring has reduced the difficulty of developers using a variety of data persistence technologies through a variety of template classes. These template classes are thread-safe, meaning that multiple DAO can reuse the same template instance without conflicts. We use the template class to access the underlying data, and depending on the persistence technology, the template class needs to bind the resources of the data connection or session. However, these resources are inherently non-thread-safe, meaning that they cannot be shared by multiple threads at the same time. Although the template class obtains a data connection or session through a resource pool, the resource pool itself addresses the caching of data connections or sessions and is not a thread-safe issue for data connections or sessions.

In the traditional experience, if an object is non-thread-safe, access to the object must be thread-synchronized with synchronized in a multithreaded environment. However, the template class does not adopt the thread synchronization mechanism because thread synchronization reduces concurrency and affects system performance. In addition, the challenge of addressing thread safety through code synchronization can be much more difficult to implement several times. What kind of magic can a template class rely on to resolve thread-safety problems without thread synchronization? The answer is threadlocal. Spring Transaction Management >

Threadlocal play an important role in spring, in the management of the request scope of the bean, transaction management, task scheduling, AOP and other modules have appeared their figure, play a pivotal role. To understand the underlying technology of spring transaction management, Threadlocal is the fortress of the hill that must be conquered.

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, as the name implies, is not a thread, but a localized object of a thread. When an object working in multi-threading uses threadlocal to maintain a variable, threadlocal assigns a separate copy of the variable to each thread that uses the variable. So each thread can change its own copy independently, without affecting the copy of the other thread. From the thread's point of view, this 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 XL, FORTRAN) provide thread-local variables at the syntactic level. Language-level support is not available in Java, and support is provided through threadlocal classes in a workaround. Therefore, the code to write thread-local variables in Java is relatively awkward, which is why thread-local variables are not well-developed among Java developers.


interface method for Threadlocal

Threadlocal class interface is very simple, there are only 4 methods, let's look at it first.
void set (object value) sets the value of the thread local variable of the current thread; public Object get () This method returns the thread local variable corresponding to the current thread, and public void remove () Removes the value of the current thread local variable. The goal is to reduce memory usage, which is a new approach to JDK 5.0.   It should be noted that, when the thread ends, the local variables on the thread should be 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 recovery; protected Object InitialValue () Returns the initial value of the thread's local variable, which is a protected method, apparently designed for 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 ().

Threadlocal is how to 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 9-3 simplethreadlocal
Java Code    Spring Transaction Management > public class simplethreadlocal {        private map valuemap = collections.synchronizedmap (New HashMap ());       public void set (object newvalue)  {       The              //① key is a thread object, and the value is a copy of the variable for this thread            valuemap.put (Thread.CurrentThread (),  newValue);        }       public object get ()  {            Thread currentThread =  Thread.CurrentThread ();                       //② returns the variable corresponding to this thread             Object o = vAluemap.get (CurrentThread);                                         //③ If it doesn't exist in the map, save it in the map                    if  (o == null && ! Valuemap.containskey (CurrentThread))  {                o = initialvalue ();                valuemap.put (Currentthread, o);            }           return o;        }       public void remove ()  {         &Nbsp;  valuemap.remove (Thread.CurrentThread ());       }       public object initialvalue ()  {            return null;       }  }  

Although the threadlocal implementation version in Listing 9 3 looks naïve, it is very 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 9-4 SequenceNumber
Java Code    Spring Transaction Management > package com.baobaotao.basic;      public class  SequenceNumber {                    //① threadlocal InitialValue () method with Anonymous inner class override, specify initial value         Private static threadlocal<integer> seqnum = new threadlocal<integer > () {           public integer initialvalue () {                return 0;           }       };                    //② get the next sequence value        public int getnextnum () {            seqnum.set (SEqnum.get () +1);           return seqnum.get ();        }              public  static void main (String[ ] args)         {              SequenceNumber sn = new  SequenceNumber ();                         //③ 3 threads sharing SN, each generating serial number              testclient t1 = new testclient (SN);    

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.