[Source] ThreadLocal relationship with the Thread

These are two very basic class, and in most cases will be used. Today, someone in the group, for that matter, the way I looked at it source.

Here it is simply the relationship between these two classes of it.

As we know, in a multithreaded environment of each Thread ThreadLocal is isolated, each has its own ThradLocal Thread copies.

Another way is through a ThreadLocal same can store and retrieve different values ​​in a multithreaded environment.

Starting from the get method ThreadLocal to see where the data is taken from

public class ThreadLocal<T> {
	...
    /**
     * 这里的 getMap 方法获取存有数据的map,并且key为当前线程
     */
    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();
    }
    
    /**
     * 存放数据的map对应 threadLocals 属性
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    ...
}
public
class Thread implements Runnable {
	...
	/* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class.
     * 这里看到上面 ThreadLocal 存放数据的map来自 Thread 的 threadLocals,并且该map由 ThreadLocal 维护
    */
    ThreadLocal.ThreadLocalMap threadLocals = null;
	...
}

Here we can sort out the relationship between the two under:
1, Thread has a map of their own, key to ThreadLocal, value is the value of
2, ThreadLocal is actually getting value obtained from the current Thread the map (to themselves as the key)

This is why ThreadLocal to keep a copy of each Thread, the data is actually placed in the Thread.

Published 107 original articles · won praise 88 · views 260 000 +

Guess you like

Origin blog.csdn.net/Code_shadow/article/details/103835230