Java class ThreadLocal Local thread variable

Source: Internet
Author: User

Preface: The work will use threadlocal, first study summarizes a wave. There is no place to welcome comments to point out.

Defined

Threadlocal is not a thread, but a local variable of thread. These variables are different from their ordinary counterparts, because each thread that accesses a variable (through its get or set method) has its own local variable, independent of the initialized copy of the variable.

Role

Each thread is implemented with its own shared variables.

How to use

  

InitialValue: Returns the initial value of the thread's local variable, which is a protected method, apparently designed to allow subclasses to overwrite, which is null by default.

Remove method: Removes the value of the current thread local variable to reduce memory usage, which is a new method of JDK 1.5. It is important to note that when the thread ends, the local variables of the thread that should be used are 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.

Source code parsing ThreadLocal construction Method:

  

InitialValue () Method:

  

Get () Method:

The first behavior gets the thread's current active thread

  

The Threadlocalmap object is then fetched to the current thread, and a key-value pair of the map object is fetched through the current threadlocal, thereby removing a copy of the variable stored in the current threadlocal.

If the Threadlocalmap object is empty, or if the map does not have a copy of the current threadlocal variable, call Setinitialvalue ();

Set () Method:

  

If the thread variable map is inside the current threads, the current thread variable (this) is set to a value (value), and if not, the thread variable map of the current thread is created and the value is set.

Getmap () Method:

  

The Getmap () method returns a variable of the current thread, threadlocals, of type Threadlocalmap.

Setinitialvalue () Method:

  

The Setinitialvalue () method, which is primarily set to initialize the variable copy of the current thread variable. If there is no current thread variable map (THREADLOCALMAP) inside the current thread, initialize the thread variable map of the current thread (thread)

Createmap () Method:

  

Initializes thread variables for the current thread (threads) map

Threadlocalmap Inner class:

  

Construction Method:

  

It can be seen from here that the key value stored in the Threadlocalmap is the ThreadLocal object.

Remove () Method:

Example of verifying the isolation of thread variables
1 /**2 * Local thread variable test3 * Created by Yule on 2018/6/26 22:35.4  */5  Public classThreadlocaltest {6      Public Static voidMain (string[] args)throwsinterruptedexception {7ThreadDemo1 ThreadDemo1 =NewThreadDemo1 ();8 Threaddemo1.start ();9 TenThread.Sleep (100); One  AThreadDemo2 ThreadDemo2 =NewThreadDemo2 (); - Threaddemo2.start (); -  theThreadLocalTools.stringThreadLocal.set ("Main setting value"); - System.out.println (ThreadLocalTools.stringThreadLocal.get ()); -     } - } +  - classthreadlocaltools{ +      Public StaticThreadlocal<string> stringthreadlocal =NewThreadlocal<>(); A } at  - classThreadDemo1extendsthread{ - @Override -      Public voidrun () { -         Super. Run (); -          for(inti = 0; I < 10; i++){ in System.out.println (ThreadLocalTools.stringThreadLocal.get ()); -ThreadLocalTools.stringThreadLocal.set ("ThreadDemo1 Setting value"); to             Try { +Thread.Sleep (100); -}Catch(interruptedexception e) { the e.printstacktrace (); *             } $         }Panax Notoginseng     } - } the  + classThreadDemo2extendsthread{ A @Override the      Public voidrun () { +         Super. Run (); -          for(inti = 0; I < 10; i++){ $ System.out.println (ThreadLocalTools.stringThreadLocal.get ()); $ThreadLocalTools.stringThreadLocal.set ("ThreadDemo2 Setting value"); -             Try { -Thread.Sleep (100); the}Catch(interruptedexception e) { - e.printstacktrace ();Wuyi             } the         } -     } Wu}

The first of the output is null because the get () method is called before the set () method, and the value of the InitialValue () method is given, which defaults to null.

Summarize

Threadlocal is a good idea to solve thread safety problems by providing a separate copy of the variable for each thread to solve the conflicting problem of variable concurrency access. In many cases, threadlocal is easier and more convenient than using the synchronized synchronization mechanism to solve thread safety problems, and results programs have higher concurrency.

Threadlocal are usually private static fields in a class that want to associate the state with a thread (for example, a user ID or transaction ID). After the thread disappears, all copies of its threaded local instances are garbage collected (unless there are other references to those replicas).

How does threadlocal maintain a copy of a variable for each thread? In fact, the idea is simple: Define a threadlocalmap in the Threadlocal class, each thread has a variable of that type--threadlocals--is used to store a variable copy of each thread, the key of the element in the map is the thread object, The value corresponds to the variable copy of the thread.

We usually define the subclass of threadlocal by means of an anonymous inner class, providing the initial value of the variable.

Java class ThreadLocal Local thread variable

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.