Home  >  Article  >  Java  >  The use of ThreadLocal in Java multi-threading

The use of ThreadLocal in Java multi-threading

不言
不言forward
2018-10-17 16:21:532483browse

The content of this article is about the use of ThreadLocal in Java multi-threading. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In a multi-threaded environment, thread synchronization must be performed when accessing non-thread-safe variables, such as using the synchronized method to access a HashMap instance. However, synchronous access will reduce concurrency and affect system performance. At this time, you can trade space for time. If we allocate an independent variable to each thread, you can use non-thread-safe variables in an asynchronous manner. We call such variables thread-local variables.

As the name suggests, thread local variables mean that each thread has its own independent copy of the variable, which cannot be accessed by other threads like ordinary local variables. Java does not provide language-level thread local variables, but provides the function of thread local variables in the class library, which is the protagonist this time ThreadLocal class.

Usage of ThreadLocal

The use of ThreadLocal in Java multi-threading

##The Java8 version of ThreadLocal has 4 shown in the figure above There are two public methods and one protected method. The first method is used to return the initial value, which is null by default. The second static method withInitial(Supplier extends S> supplier) is newly added in Java8 version, and the next three instance methods are very simple.

Before Java8, when using ThreadLocal and want to set the initial value, you need to inherit the ThreadLocal class and override the protected T initialValue() method. For example:


ThreadLocal<integer> threadLocal = new ThreadLocal<integer>() {
    @Override
    protected Integer initialValue() {
        return 0;
    }
};</integer></integer>
can be used in the Java8 version The newly added static method withInitial(Supplier extends S> supplier) is very convenient to set the initial value, for example:

ThreadLocal<integer> threadLocal = ThreadLocal.withInitial(() -> 0);

System.out.println(threadLocal.get());
threadLocal.set(16);
System.out.println(threadLocal.get());
threadLocal.remove();
System.out.println(threadLocal.get());

// 同一个线程的输出
0
16
0
Process finished with exit code 0</integer>

The principle of ThreadLocal

Then ThreadLocal is How to implement the function of thread local variables? In fact, the basic principle of ThreadLocal is not very complicated. ThreadLocal internally defines a static class ThreadLocalMap. The key of ThreadLocalMap is the ThreadLocal object. The value of ThreadLocalMap is the value stored by ThreadLocal. However, this ThreadLocalMap is maintained in the Thread class. Let’s take a look at some of the source code of ThreadLocal:

    // ThreadLocal的set方法
    public void set(T value) {
        // 获取当前线程对象
        Thread t = Thread.currentThread();
        // 获取Map
        ThreadLocalMap map = getMap(t);
        if (map != null)
            // 设置值
            map.set(this, value);
        else
            // 初始化Map
            createMap(t, value);
    }
    
    // ThreadLocal的createMap方法
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
    
    // Thread类定义的实例域
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;
It can be seen that the core implementation of ThreadLocal is the implementation of ThreadLocalMap. ThreadLocalMap internally declares an Entry class to store data:

static class Entry extends WeakReference<threadlocal>> {
    /** The value associated with this ThreadLocal. */
    Object value;

    Entry(ThreadLocal> k, Object v) {
        super(k);
        value = v;
    }
}</threadlocal>
ThreadLocalMap implementation There are similarities with the implementation of HashMap. For example, arrays are also used to store data and automatically expand. The difference is that the hash algorithm and the processing after hash collision are different.

        // ThreadLocalMap的set方法
        private void set(ThreadLocal> key, Object value) {

            Entry[] tab = table;
            int len = tab.length;
            // 计算在Entry[]中的索引,每个ThreadLocal对象都有一个hash值threadLocalHashCode,每初始化一个ThreadLocal对象,hash值就增加一个固定的大小0x61c88647
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal> k = e.get();
                // 如果键已存在就更新值
                if (k == key) {
                    e.value = value;
                    return;
                }
                // 代替无效的键
                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }
        
        private static int nextIndex(int i, int len) {
            return ((i + 1 You can see that ThreadLocalMap treats the Entry[] array as a ring. Starting from the calculated index position, if the index already has data, it will be judged whether the Key is the same, and if it is the same, the value will be updated. Otherwise, just wait until you find an empty position and put the value in it. The same is true when obtaining values. Starting from the calculated index position, one by one is checked to see if the keys are the same. If there are many hash collisions, the performance may not be very good. <p></p><p>The application of ThreadLocal<strong></strong><code><br></code></p><p>##The application of ThreadLocal is very wide, for example, Java engineers are very familiar with it ThreadLocal is used in the Spring framework to encapsulate non-thread-safe stateful objects, so we can declare most beans as singleton scope. When writing multi-threaded code, we can also think about whether it is better to access non-thread-safe stateful objects in a synchronous manner, or whether it is better to use ThreadLocal to encapsulate non-thread-safe stateful objects. <code><span style="font-family: 微软雅黑, Microsoft YaHei;"></span><br></code></p><p class="comments-box-content"></p>

The above is the detailed content of The use of ThreadLocal in Java multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete