Principle of ThreadLocal mode: threadlocal Mode

Source: Internet
Author: User

Principle of ThreadLocal mode: threadlocal Mode

In earlier versions of JDK, a solution is provided to solve the problem of multi-thread concurrency: java. lang. ThreadLocal class. When maintaining variables, the ThreadLocal class actually uses an independent copy of ThreadLocalMap in the current Thread. Each Thread can independently modify its own copy without affecting each other, this isolates threads and threads to avoid conflicts between variables accessed by threads.

ThreadLocal is not a thread, but is isolated from other threads by operating an internal variable in the current thread. ThreadLocal indicates that the operation object is a local variable of the thread.

 

Thread. java

Public class Thread implements Runnable {// many other code ThreadLocal. ThreadLocalMap threadLocals = null is omitted here ;}

 

ThreadLocal. java

Public class ThreadLocal <T> {// many other codes are omitted here. // Save the value to the local variable of the current thread. public void set (T value) {// obtain the current Thread t = Thread. currentThread (); // call the getMap method to obtain the local variable ThreadLocalMap map = getMap (t) in the current thread; // if ThreadLocalMap already exists, directly use if (map! = Null) // use the current ThreadLocal instance as the key and store it in the current thread's // ThreadLocalMap. If the current thread defines multiple different ThreadLocal // instances, they are stored as different keys without interfering with map. set (this, value); else // If ThreadLocalMap does not exist, a new createMap (t, value) is created for the current thread );} // get the variable value public T get () {// get the current Thread t = Thread. currentThread (); // obtain ThreadLocalMap map = getMap (t) in the current thread; if (map! = Null) {// obtain the variable value ThreadLocalMap. Entry e = map. getEntry (this) in the current thread with the current ThreadLocal instance as the key; if (e! = Null) return (T) e. value;} // when map does not exist, set the initial value return setInitialValue ();} // obtain the corresponding ThreadLocalMap getMap (Thread t) {return t from the current Thread. threadLocals;} // create ThreadLocalMap void createMap (Thread t, T firstValue) in the current Thread {// call the constructor to generate ThreadLocalMap t in the current Thread. threadLocals = new ThreadLocalMap (this, firstValue);} // ThreadLoaclMap definition static class ThreadLocalMap {// a lot of code is omitted here }}

 

  • The ThreadLocalMap variable belongs to the internal attributes of the thread. Different threads have completely different ThreadLo-calMap variables.
  • The value of the ThreadLocalMap variable in the thread is created when the ThreadLocal object performs the set or get operation.
  • Before creating ThreadLocalMap, check whether the ThreadLocalMap variable in the current thread already exists. If it does not exist, create one. if it already exists, use the ThreadLo-calMap created by the current thread.
  • The key to using ThreadLocalMap of the current thread is to use the current ThreadLocal instance as the key for storage.

 

ThreadLocal achieves Data Access isolation in at least two aspects: horizontal isolation and vertical isolation.

  • Vertical isolation-data access between threads is isolated. This is ensured by the data structure of the thread. Because each thread accesses the ThreadLocalMap of each thread during object access.
  • Horizontal isolation-objects operated by different Thread-Local instances in the same Thread are isolated from each other. This is ensured by ThreadLocalMap using the current ThreadLocal instance as the key during storage.

 

In-depth comparison of ThreadLocal mode and synchronized keywords

  • ThreadLocal is a Java class. It uses operations on local variables in the current thread to solve variable access conflicts between different threads. Therefore, ThreadLocal provides a thread-safe shared object mechanism, with each thread having its copy.
  • Synchronized in Java is a reserved word. It relies on the JVM locking mechanism to implement functions or variables in the critical section in access atomicity. In the synchronization mechanism, the object lock mechanism ensures that only one thread accesses the variable at a time. At this time, the variables used as the "Lock Mechanism" are shared by multiple threads.
  • The synchronization mechanism (the synchronized keyword) uses the "time-for-space" method to provide a variable for different threads to queue for access. ThreadLocal uses the space-for-time method to provide a copy of the variable for each thread, so as to achieve simultaneous access without affecting each other.

To complete the ThreadLocal mode, the most important thing is to create a ThreadLocal instance that can be accessed anywhere. This can be achieved through class variables. The class used to carry class variables is considered as a shared environment.

 

Public class Counter {// create a static ThreadLocal variable and use the get method to change it to an accessible object private static ThreadLocal <Integer> counterContext = new ThreadLocal <Integer> () {protected synchronized Integer initialValue () {return 10 ;}}; // use the static get method to access the public static Integer get () {return counterContext stored in ThreadLocal. get () ;}// set the variable value to public static void set (Integer value) {counterContext through the static set method in ThreadLocal. set (value) ;}// encapsulate the business logic. The variable public static Integer getNextCounter () {counterContext is stored in ThreadLocal. set (counterContext. get () + 1); return counterContext. get ();}}

 

public class ThreadLocalTest extends Thread {    public void run() {        for (int i = 0; i < 3; i++) {            System.out.println("Thread[" + Thread.currentThread().getName() + "],counter=" + Counter.getNextCounter());        }    }}

 

public class Test {    public static void main(String[] args) throws Exception {        ThreadLocalTest testThread1 = new ThreadLocalTest();        ThreadLocalTest testThread2 = new ThreadLocalTest();        ThreadLocalTest testThread3 = new ThreadLocalTest();        testThread1.start();        testThread2.start();        testThread3.start();    }}

 

Let's run the above Code and see the output result:

Thread [Thread-2], counter = 11Thread [Thread-2], counter = 12Thread [Thread-2], counter = 13Thread [Thread-0], counter = 11Thread [Thread-0], counter = 12Thread [Thread-0], counter = 13Thread [Thread-1], counter = 11Thread [Thread-1], counter = 12Thread [Thread-1], counter = 13

 

ThreadLocal is the most suitable scenario: share data at different development layers of the same thread.

Two main steps of ThreadLocal mode:

  • Create a class and encapsulate a static ThreadLocal variable in it to make it a shared data environment.
  • Implement a static method (set value and value) to access the static ThreadLocal variable in the class ).

 

 

To be continued...

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.