Java Concurrent Programming: thread-gated--threadlocal

Source: Internet
Author: User
Tags closure

One: Thread closure

Thread closure: When accessing shared mutable data, synchronization is usually required. One way to avoid synchronization is to not share data. If data is accessed only in single-wire range, no synchronization is required, a technique known as thread closure

Thread closure Technology A common application is the JDBC Connection object, and the JDBC specification does not require that the connection object be thread-safe, and in a server application, the thread obtains a connection object from the connection pool. Returns the object to the connection pool when it is finished. Here are a few thread-blocking techniques:

1:ad-hoc Thread Closure

2: Stack closure

A stack closure is a type of thread closure that can only be accessed by local variables in a stack closure. One of the intrinsic properties of a local variable is that it is enclosed in the execution stack, and other threads cannot access the stack, and the stack closure is also known as thread internal use or thread-local use. In short, it is a local variable. Multiple threads access a method, and the local variables in this method are copied one minute to the line stacks. So local variables are not shared by multiple threads, and there is no concurrency problem. So we can use local variables to not use global variables, global variables easily cause concurrency problems.

3: A more canonical way to maintain thread closeness is to use the ThreadLocal class, which associates a value in a thread with the object that holds the value. The Threadlocal class provides access interfaces or methods such as get and set, which have a separate copy of each thread that uses the variable, so get always puts back the current execution thread's latest value in invoking set settings.

We usually use threadlocal to ensure that mutable singleton variables and global variables are not shared by multithreading. Threadlocal is almost the best choice if many of our operations frequently use an object, and we need to consider its thread closure and its initialization overhead.

Two: ThreadLocal

  First, ThreadLocal is not used to solve multi-threaded access problems with shared objects, and in general, objects in the thread through Threadlocal.set () are objects that the thread itself uses, and other threads do not need access or access. different objects are accessed in each thread.

In addition, it is said that threadlocal enables each thread to maintain its own independent object, not by Threadlocal.set (), but by creating an object through the operation of the new object in each thread, creating one for each thread, is not a copy or copy of any object. the reference to this newly created object is saved to a map of each thread by Threadlocal.set (), each thread has a map that executes Threadlocal.get (), and each thread pulls the object from its own map and So the objects in their own thread are taken out, and the threadlocal instance is used as the key to the map.

Second, look at the two classic applications of threadlocal, respectively, for session management and database connection creation.

1     Private Static FinalThreadLocal threadsession =NewThreadLocal ();2 3      Public StaticSession getsession ()throwsinfrastructureexception {4Session s =(Session) threadsession.get ();5         Try {6             if(s = =NULL) {7s =getsessionfactory (). Opensession ();8 Threadsession.set (s);9             }Ten}Catch(Hibernateexception ex) { One             Throw NewInfrastructureexception (ex); A         } -         returns; -}

As you can see in the GetSession () method, first determine if there is a session in the current thread, and if not, then use Sessionfactory (). Opensession () to create a session and then the session Set into a thread, it is actually placed in the current thread's threadlocalmap this map, when the only reference to the session is the current thread of the Threadlocalmap (as described below), And threadsession as the key of this value, to get this session can be obtained by Threadsession.get (), the operation is actually to get the threadlocalmap in the current thread, The threadsession is then removed as a key by the corresponding value. This session is equivalent to the private variable of the thread, not public.
Obviously, other threads are not able to get this session, and they can only take things from their own threadlocalmap. If the session is shared with multiple threads, it's not a mess.
Imagine how to achieve it without threadlocal? It may be troublesome to create a session in action and then upload the session to the service and DAO. Or you can define a static map, the current thread as a key, the creation of the session as a value, put into the map, it should be OK, this is the general idea, but in fact, the implementation of Threadlocal is the opposite, it is in each thread has a map, And the threadlocal instance as key, so that the number of items in each map is very small, and when the thread is destroyed when the corresponding things are also destroyed, do not know what other advantages besides these.

1 Private StaticThreadlocal<connection>Connectionholder2=NewThreadlocal<connection>() {3  PublicConnection InitialValue () {4     returndrivermanager.getconnection (db_url);5 }6 };7  8  Public StaticConnection getconnection () {9 returnconnectionholder.get ();Ten}

Three: Source code analysis

The specific source code analysis can be seen in the following blog content, written very comprehensive:

Http://www.cnblogs.com/dolphin0520/p/3920407.html

Java Concurrent Programming: thread-gated--threadlocal

Related Article

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.