Home > Java > javaTutorial > body text

What is ThreadLocal? Principle analysis of ThreadLocal

不言
Release: 2018-10-11 16:38:07
forward
10856 people have browsed it

This article brings you what is ThreadLocal? The principle analysis of ThreadLocal has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is ThreadLocal?

ThreadLocal provides thread local variables. These variables differ from ordinary variables in that each thread that accesses such a variable (through its get or set method) has its own, independently initialized copy of the variable.

ThreadLocal instances are usually private static fields of classes that wish to associate state with a thread (for example, user ID or Transaction ID, etc.).

(Voiceover: This passage expresses three meanings

1. ThreadLocal is a variable type, which we call "thread local variables".

2. When each thread accesses such a variable, it will create a copy of the variable. This variable copy is private to the thread.

3. ThreadLocal type variables are generally modified with private static.)

For example , in the following example this class generates a unique identifier for each thread. The ID of a thread is specified by the first time it calls the ThreadId.get() method.

package com.cjs.example;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadId {
    private static final AtomicInteger nextId = new AtomicInteger(0);
    private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return nextId.getAndIncrement();
        }
    };
    public static int get() {
        return threadId.get();
    }
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getId());
                }
            }).start();
        }
    }
}
Copy after login

2. ThreadLocal main operations

/**
 * 返回当前线程对ThreadLocal变量的“初始值”
 * 这个方法将在线程第一次访问变量(通过调用get方法)时被调用,如果之前已经调用过了就不会再调了
 *
 * @return the initial value for this thread-local
 */
protected T initialValue() {
    return null;
}

/**
 * 设置当前线程的ThreadLocal变量的副本为指定的值
 *
 * @param value the value to be stored in the current thread&#39;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);
}
/**
 * 返回当前线程的ThreadLocal变量副本的值
 *
 * @return the current thread&#39;s value of this thread-local
 */
public T get() {
    Thread t = Thread.currentThread();
    ThreadLocalMap map = getMap(t);
    if (map != null) {
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}

/**
 * 删除当前线程的ThreadLocal变量副本的值
 */
public void remove() {
    ThreadLocalMap m = getMap(Thread.currentThread());
    if (m != null)
        m.remove(this);
}
Copy after login

3. Read the source code

3.1. set method

## is OK As you can see, the bottom layer of ThreadLocalMap is an array, and the element type in the array is Entry type.

The set operation is to set the value to the member variable threadLocals of the ThreadLocal.ThreadLocalMap type of the current thread. The key is this and the value is what we specified. Value

Note that this passed here represents the ThreadLocal type variable (or object)

In other words, each thread maintains an object of ThreadLocal.ThreadLocalMap type , and the set operation actually uses the ThreadLocal variable as the key, the value we specify as the value, and finally encapsulates this key-value pair into an Entry object and puts it in the ThreadLocal.ThreadLocalMap object of the thread. Each ThreadLocal variable in this thread is an Entry in the ThreadLocal.ThreadLocalMap object. Since each ThreadLocal variable corresponds to an element in ThreadLocal.ThreadLocalMap, these elements can be read, written and deleted.

3.2. get method

The get() method is to retrieve the corresponding ThreadLocal variable from the ThreadLocal.ThreadLocalMap object of the current thread The corresponding value

Similarly, the remove() method is to clear this value

If represented graphically, it probably looks like this:

Or something like this:

4. ThreadLocal usage scenarios

Transfer values ​​within the thread life cycle

Finally, everything Credit to ThreadLocalMap

The above is the detailed content of What is ThreadLocal? Principle analysis of ThreadLocal. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template