ThreadLocal: simple understanding and threadlocal understanding

Source: Internet
Author: User

ThreadLocal: simple understanding and threadlocal understanding
In the code of the java open-source project, you can see the ThreadLocal attribute in a class:

private static ThreadLocal<Boolean> clientMode = new ThreadLocal<>();


I saw ThreadLocal while reading a book, but suddenly I couldn't remember its usefulness .. I was surprised to find that I had read the book. So I checked it online immediately.

It originally meant the local variable of the thread. ThreadLocal is more like a tool class for accessing the thread variable. So why is this method used?Looking at Java concurrent programming practices, we can see that local variables in the thread are usually used to prevent incorrect sharing in the Design of Variable Singleton or global variables. It seems so stiff. The example is the JDBC Connection application. For a single-threaded program, Connection is generally created at startup, so that you do not need to create objects every time. But changing to a multi-threaded environment won't work, because the JDBC specification does not require Connection to be thread-safe. To solve this problem, you can use ThreadLocal. With ThreadLocal, you can create a Connection object in each thread to meet thread security requirements. What I'm curious about here is how ThreadLocal does this? ThreadLocal implementationOpen the source code. ThreadLocal is a generic class, and it is not complicated. The constructor does nothing. The most common methods in ThreadLocal are set and get. The main mystery is the following lines of code:
private final int threadLocalHashCode = nextHashCode();     /**     * The next hash code to be given out. Updated atomically. Starts at     * zero.     */    private static AtomicInteger nextHashCode =        new AtomicInteger();     /**     * The difference between successively generated hash codes - turns     * implicit sequential thread-local IDs into near-optimally spread     * multiplicative hash values for power-of-two-sized tables.     */    private static final int HASH_INCREMENT = 0x61c88647;     /**     * Returns the next hash code.     */    private static int nextHashCode() {        return nextHashCode.getAndAdd(HASH_INCREMENT);    }

The threadLocalHashCode variable will be created along with the ThreadLocal construction, and the variable initialized is a nextHashCode () method. From the nextHashCode method, we know that an addition operation is performed on an integer variable nextHashCode, but the HASH_INCREMENT size is fixed.

What does this mean? In fact, a new hash value is generated every time ThreadLocal is created, which means that each object is different. So what is the use? Let's take a look at the set method, because this method is ThreadLocal to set the variable to the method in the thread:
/**     * Sets the current thread's copy of this thread-local variable     * to the specified value.  Most subclasses will have no need to     * override this method, relying solely on the {@link #initialValue}     * method to set the values of thread-locals.     *     * @param value the value to be stored in the current thread's copy of     *        this thread-local.     */    public void set(T value) {        Thread t = Thread.currentThread();        ThreadLocalMap map = getMap(t);        if (map != null)            map.set(this, value);        else            createMap(t, value);    }

You can see the execution process of the method:

1. Obtain the instance of the current thread 2. then obtain the ThreadLocalMap object from the thread, this is the place where local variables are stored in the thread. 3. If map is not empty, the value is written to the map. The key is the current ThreadLocal object. 4. If it is null, when creating a map, the value will also be written to the map. The key is also a ThreadLocal object. In fact, ThreadLocal generates a new object each time, to ensure that each thread is targeted at a ThreadLocal object. Then, the data is written to threadLocals in the thread through the set method to ensure thread security. Of course, the written value must not be a shared object; otherwise, thread security cannot be guaranteed. Reference: "java concurrent programming practice" Correct Understanding ThreadLocal: http://www.iteye.com/topic/103804 Note: This article is original, welcome to reprint, please in the Article Page obvious position to give this article link! If you think this article is good, please click the recommendation in the lower right corner. Thank you very much! Http://www.cnblogs.com/5207

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.