Java ThreadLocal

来自WHY42
Riguz留言 | 贡献2021年4月29日 (四) 09:37的版本 →‎ThreadLocal原理

ThreadLocal原理

每个Thread中维护了一个的对象来存储:

  • 这个变量默认是null,会在线程第一次调用get方法的时候初始化。
  • 这个map维护了ThreadLocal对象与值的映射。map.set(this, value);
    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 values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

ThreadLocal instance does not keep but provides the access to thread-specific value using itself as a key.

WeakReference

这个map中的key使用了WeakReference,

static class Entry extends WeakReference<ThreadLocal<?>>