Thread local variable threadlocal source code interpretation

Source: Internet
Author: User

First, threadlocal basic knowledge


Raw thread Status: According to the traditional experience, if an object is non-thread-safe, in a multithreaded environment, access to the object must be thread-synchronized with synchronized. However, the various template classes in spring do not adopt the thread synchronization mechanism, because thread synchronization can affect concurrency and system performance, and it is difficult to implement.

Threadlocal plays an important role in spring. It appears in modules that manage the request scope of beans, transaction management, task scheduling, and AOP.

Threadlocal Introduction: It is not a thread, but a localized object of a thread, or a local variable. 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, putting the class variable into an object of type threadlocal, making the variable have a separate copy in each thread, and not having a thread reading the variable and being modified by another thread.

How do I store thread local variables?

There is a threadlocalmap in the Threadlocal class that holds a copy of the variable for each thread, the key of the element in the map is the thread object, and the value is a copy of the variable of the corresponding thread.

Second, the source code interpretation


 

First of all, the value of threadlocal stored in the thread is shared among the threads mutually exclusive, mainly used to share some data within the thread, to avoid passing parameters, so that after processing, can gracefully solve some practical problems, such as hibernate in the Opensessioninview, is to use Threadlocal to save the session object, and we often use threadlocal store connection, code such as:

1/** 2 * Database Connection Management Class 3 * @author Cool 4 * 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;  -    }   -       -    /** 28 * Close the current database connection*/   -     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 NotoginsengConn.close ();  -                //Remove Connection theThreadlocal.remove ();  +conn =NULL;  A            }   the}Catch(SQLException e) { +            //Exception Handling -        }   $    }  } 

The benefits of such treatment:

1 Unified management Connection;

2 No need to display the connection, the code is more elegant;

3 Reduction of coupling.

Threadlocal has four methods, respectively:

InitialValue

Protected T 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 get the local variable for each of the threads, that is, the first time the thread accesses the variable using the Get () method. If the thread calls the set (T) method before the Get method, then the InitialValue method is not called in the 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

Public T 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

public void 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 the InitialValue () method to set the value of a thread-local variable.

Parameters:

Value-values stored in the current thread copy of this thread's local variables.

Remove

public void 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:

/** * Sets the current thread's copy of this thread-local variable * to the specified value.  Most subclasses would have a no need to * override this method, relying solely on the {@link #initialValue} * method to set  The values of thread-locals.  * * @param value The value of the stored in the current thread's copy of * this thread-local. */   Public void Set(T value) {//gets the current thread objectThread T =Thread.CurrentThread (); //gets the current thread local variable mapThreadlocalmap map =Getmap (t); //map is not empty    if(Map! =NULL)          //stored valueMap.Set( This, value); Else          //Create a current thread local variable mapCreatemap (t, value); }    /** Get The map associated with a ThreadLocal.  Overridden in * inheritablethreadlocal. * * @param t the current thread * @return the map*/threadlocalmap Getmap (Thread t) {//gets the local variable map for the current thread    returnt.threadlocals; } 

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:

/** * Returns the value in the current thread's copy of this * thread-local variable. If the variable have no value for the ' current thread ', it is first initialized to the value returned * by an invocation  Of the {@link #initialValue} method. * * @return The current thread ' s value of this thread-local*/   PublicTGet() {Thread T=Thread.CurrentThread (); Threadlocalmap Map=Getmap (t); if(Map! =NULL) {threadlocalmap.entry e= Map.getentry ( This); if(E! =NULL)              return(T) E.value; }      //if the value is null, the initial value is returned    returnSetinitialvalue (); }  

The previous set method analysis, the Get method is also the same, it should be explained that if the set operation is not done, 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

Excellent blog:

ThreadLocal

Thread local variable threadlocal source code interpretation

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.