Java. lang. ThreadLocal

Source: Internet
Author: User

Java. lang. ThreadLocal


1. Overview
What is ThreadLocal? In fact, ThreadLocal is not a local implementation version of a Thread, it is not a thread, but Thread local variable (thread local variable ). It may be more appropriate to name it ThreadLocalVar. ThreadLocal provides a copy of the variable value for every thread that uses the variable. It is a special thread binding mechanism in Java, is that each thread can independently change its own copy, without conflict with the copies of other threads.


From the thread perspective, each thread maintains an implicit reference to its local variable copy, as long as the thread is active and the ThreadLocal instance is accessible. After the thread disappears, all copies of the local instance of the thread will be garbage collected (unless there are other references to these copies ).


Data accessed through ThreadLocal is always related to the current thread. That is to say, JVM binds a private local instance access space for each running thread, this provides an isolation mechanism for concurrent access problems that often occur in multi-threaded environments.


How does ThreadLocal maintain copies of variables for each thread? In fact, the implementation idea is very simple. There is a Map in the ThreadLocal class, which is used to store copies of the variables of each thread.


To sum up, for the multi-thread Resource Sharing problem, the synchronization mechanism adopts the "Time for space" approach, while ThreadLocal adopts the "space for Time" approach. The former provides only one copy of the variable, allowing different threads to queue for access, while the latter provides a copy of the variable for each thread. Therefore, the former can be accessed simultaneously without affecting each other.


2. API description
ThreadLocal ()
Create a local variable of the thread.
T get ()
Returns the value in the current thread copy of the local variable of this thread. If this is the first time the thread calls this method, it is created and initialized.
Protected T initialValue ()
Returns the initial value of the current thread for the local variable of this thread. This method can be called at most once each time the thread is accessed to obtain the local variable of each thread, that is, the first time the thread uses the get () method to access the variable. If the thread calls the set (T) method before the get method, the initialValue method is not called in the thread. If this implementation only returns null, if the programmer wants to initialize a local variable of the thread to a value other than null, the programmer must create a subclass for ThreadLocal and override this method. Typically, anonymous internal classes are used. The typical Implementation of initialValue calls an appropriate constructor and returns the newly constructed object.
Void remove ()
Remove the local variable value of this thread. This may help reduce the need to store local variables in the thread. If you access the local variable of this thread again, it will own its initialValue by default.
Void set (T value)
Set the value in the current thread copy of the local variable of this thread to the specified value. Many applications do not need this function. They only rely on the initialValue () method to set the value of the local variable of the thread.


In programs, the initialValue method is generally rewritten to give a specific initial value.


3. Example
View sourceprint? 01 public class ThreadLocalTest {

02 private static ThreadLocal <String> val = new ThreadLocal <String> ();

03

04 public static class Thread1 extends Thread {

05 private String name;

06 public Thread1 (String name ){

07 this. name = name;

08}

09 public void run (){

10 System. out. println (name + "Initial Value:" + val. get ());

11 val. set ("v [" + name + "]");

12 System. out. println (name + "after setting:" + val. get ());

13}

14}

15

16 public static class Thread2 extends Thread {

17 private String name;

18 public Thread2 (String name ){

19 this. name = name;

20}

21 public void run (){

22 System. out. println (name + "Initial Value:" + val. get ());

23 val. set ("v [" + name + "]");

24 System. out. println (name + "after setting:" + val. get ());

25}

26}

27

28 public static void main (String [] args ){

29 val. set ("123 ");

30 System. out. println ("Set Value in main program:" + val. get ());

31

32 (new Thread1 ("A1"). start ();

33 (new Thread1 ("A2"). start ();

34 (new Thread2 ("B1"). start ();

35}

36}

 


Running result:
Set the value in the main program: 123
A1 Initial Value: null
A1: v [A1]
Initial B1 value: null
A2 Initial Value: null
Value After B1 is set: v [B1]
A2: v [A2]


4. Summary
ThreadLocal is used to solve data inconsistency caused by concurrency in multiple threads. ThreadLocal provides a copy of the data concurrently accessed by each thread and runs the business by accessing the copy. This results in memory consumption, which greatly reduces the performance consumption caused by thread synchronization, it also reduces the complexity of thread concurrency control.


ThreadLocal cannot use the atomic type, but can only use the Object type. ThreadLocal is much easier to use than synchronized.


Both ThreadLocal and Synchonized are used to solve multi-thread concurrent access. However, ThreadLocal is essentially different from synchronized. Synchronized uses the lock mechanism to allow a variable or code block to be accessed by only one thread at a time. ThreadLocal provides a copy of the variable for each thread, so that each thread does not access the same object at a certain time, thus isolating multiple threads from sharing data. Synchronized, on the contrary, is used to obtain data sharing when multiple threads communicate.


Synchronized is used for data sharing between threads, while ThreadLocal is used for data isolation between threads.


Of course, ThreadLocal cannot replace synchronized. They process different problem domains. Synchronized is used to implement synchronization mechanism, which is more complex than ThreadLocal.

Author: "NullOn's blog"
 

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.