Java Multithreading-thread closure

Source: Internet
Author: User

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 on a single-wire range, synchronization is not required, a technique known as thread closure (threads confinement)

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

Ad-hoc thread closure means that the responsibility for maintaining a thread's closeness is fully assumed by the program implementation, is very fragile, so use less in the program, generally use stronger thread blocking technology, such as the stack closed or threadlocal class.

2, Stack closed  

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.

For example, the following:

View Code

Instantiates a TreeSet object in Loadtheark and saves a reference to the object in animals. At this point, there is only one reference to the collection animals, which is enclosed in a local variable and is therefore enclosed in a local variable. However, if a reference to the collection animals (or any internal data within that object) is published, the closure is destroyed and the object animals escaped.

3, Threadlocal class

  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. Take a look at the following code example:

View Code

By calling the Connectionmanager.getconnection () method, each thread acquires a copy of the connection object that it has independently owned, and the first time it gets through the InitialValue () The return value of the method to set the value. The Connection object set through the Connectionmanager.setconnection (Connection conn) method is also bound only to the current thread. This enables complete isolation of the connection object in multiple threads. When managing connection objects in a multithreaded environment in a spring container, the idea is very similar to the code above.

How does each thread bind to a copy of the connection object? Where the copy of this object is stored. When a thread first invokes the Get method of the Threadlocal class, it calls InitialValue to get the initial value, and conceptually we can think of threadlocal<t> as containing Map<thread, t> objects, The values that are specific to that thread are saved, but the threadlocal implementation is not so, just for our convenience.

Let us analyze the source code of ThreadLocal class . The Threadlocal class method is simple, only four, respectively, Set,get,remove, initialvalue, literally we can understand the role of these methods.

  Public T Get (): returns the local variable that corresponds to the current thread.

  Public void Set (T arg0): Sets the value of the current thread local variable.

  Remove () public void: removes the value of the current thread local variable to reduce memory usage, which is a new method of JDK 5.0. Note 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 reclamation.

  protected T InitialValue (): initializes the thread local variable and returns the initial value. is the protected property, which is apparently overridden by subclasses to overwrite it, and is only called when the set and get methods are called for the first time.

Below we analyze the source code of these four methods to see how the Threadlocal class implements this "to provide a different copy of the variable for each thread".

3.1 Set method

  The following is the source of the Set method

View Code

As you can see from the set method, get the current thread first: Thread arg1 = Thread.CurrentThread ();

Gets the current thread's ThreadLocalMap:ThreadLocal.ThreadLocalMap arg2 = This.getmap (arg1);

Determines whether Threadlocalmap is empty, is not empty, sets the value as a key-value pair, and key is This,value is a copy of the local variable, this is the threadlocal class instantiation object held by the current thread.

If empty, it is created by the Createmap method.

Let's look at the source code for the Getmap and Createmap methods:

View Code

It is very clear from the code that each thread has its own copy of the local variable, which is present in Threadlocalmap, where the key value is the threadlocal class instantiation object. This means that each thread has its own threadlocalmap,threadlocalmap, which is a copy of the local variable. Let's take a look at Java.lang.Thread source code.

View Code

3.2 Get method

View Code

From the code point of view, the first two steps and the set method is a kind, get the current thread and the current thread Threadlocalmap, the third step to determine whether the threadlocalmap is empty, not empty according to the this key value to get value, For air conditioning with Setinitialvalue () method.

The following is the Setinitialvalue method code:

View Code

In Setinitialvalue called the InitialValue () method, that is, the subclass to override the overridden method, the code corresponding to the above example is:

View Code

Then gets the current thread and the current thread's threadlocalmap,threadlocalmap is null to call Createmap, otherwise calls the Set method.

3.3 Summary

  The Threadlocalmap object is looking for the key with the Threadlocal object pointed to by this, which is, of course, echoing the code of the previous set () method.

Further, we can create different threadlocal instances to implement multiple variable access isolation between different threads, why can we do this? Because different threadlocal objects are different keys, you can certainly set different values in the Threadlocalmap object of the thread. By Threadlocal objects, you can share a value and multiple values in multiple threads, just as you would store a key-value pair and multiple key-value pairs in a HashMap object.

It is also said that each thread has a threadlocalmap, which accesses a local variable, and the local variable is declared with the ThreadLocal class, the thread will be new ThreadLocal (), The object of the Threadlocal class is then used as the key value, and the corresponding local variable is saved to Threadlocalmap as the value. When a thread accesses more than one threadlocal class to declare a local variable, there are multiple key-value pairs in the Threadlocalmap. Each thread has its own threadlocalmap to achieve the purpose of isolation.

When a thread terminates, the threadlocalmap of the line thread is also recycled, so there is no need to worry about memory leaks at all.

If the object instance of multi-threaded access is a singleton, or only one can be created, then the synchronization mechanism (synchronized) is used honestly.

Java Multithreading-thread closure

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.