Java concurrency: ThreadLocal and javathreadlocal of the thread synchronization mechanism

Source: Internet
Author: User

Java concurrency: ThreadLocal and javathreadlocal of the thread synchronization mechanism

1. ThreadLocal

ThreadLocal instances are usually used as static private static fields in a class, which is used to associate a thread. ThreadLocal is a local variable at the Thread level. The following are the key points of ThreadLocal variables:

A. When ThreadLocal is used to maintain A variable, if multiple threads access the ThreadLocal instance, ThreadLocal provides an independent copy of the variable for each thread that uses the variable, therefore, each thread can change its own copy independently without affecting the copies corresponding to other threads.

B. From the thread perspective, the target variable is like the Local variable of the thread, which is also the meaning of the Local variable in the class name.

 

2. Take a closer look at ThreadLocal

The ThreadLocal <T> class is very simple and has only four methods:

(1) void set (T value), which is used to set the copy of the variable in the current thread

(2) public T get (). This method is used to obtain a copy of the variable that ThreadLocal saves in the current thread.

(3) public void remove (). This method is used to remove copies of variables in the current thread to reduce memory usage. This method is newly added to JDK 5.0. It should be noted that when the thread ends, the local variables of the corresponding thread will be automatically reclaimed, so explicitly calling this method to clear the local variables of the thread is not a required operation, but it can speed up memory recovery.

(4) protected T initialValue (). This method is a protected method, which is generally used for rewriting during use. It is a delayed loading method, the default implementation in ThreadLocal directly returns a null value.

 

3. ThreadLocal example

The simple method is as follows:

Package com. test; public class ThreadMain {// ① use an anonymous internal class to overwrite the initialValue () method of ThreadLocal and specify the initial value private static ThreadLocal <Integer> seqNum = new ThreadLocal <Integer> () {public Integer initialValue () {return 0 ;}; // ② obtain the next sequence value public int getNextNum () {seqNum. set (seqNum. get () + 1); return seqNum. get () ;}public static void main (String [] args) {ThreadMain sn = new ThreadMain (); // 3 threads share the sn, their respective serial numbers are TestClient t1 = new TestClient (sn); TestClient t2 = new TestClient (sn); TestClient t3 = new TestClient (sn); t1.start (); t2.start (); t3.start ();} private static class TestClient extends Thread {private ThreadMain sn; public TestClient (ThreadMain sn) {this. sn = sn;} public void run () {for (int I = 0; I <3; I ++) {// ④ each thread generates three sequence values: System. out. println ("thread [" + Thread. currentThread (). getName () + "] --> sn [" + sn. getNextNum () + "]") ;}}}

The result is as follows:

thread[Thread-0] --> sn[1]thread[Thread-2] --> sn[1]thread[Thread-1] --> sn[1]thread[Thread-2] --> sn[2]thread[Thread-0] --> sn[2]thread[Thread-2] --> sn[3]thread[Thread-1] --> sn[2]thread[Thread-1] --> sn[3]thread[Thread-0] --> sn[3]

 

4.ThreadLocalImplementation Mechanism

This part of content has not been studied in depth, for more information, please refer to the http://www.importnew.com/17849.html

(1) the source code of the get () method is as follows:

 

5. Summary

ThreadLocal is usually declared in static variables. If you constantly create ThreadLocal without calling its remove method, memory leakage will occur, especially in highly concurrent Web containers.

ThreadLocal is easier and easier to solve thread security issues than synchronized synchronization mechanism when processing local variables of a thread, and the program has a higher concurrency.

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.