Java ThreadLocal

来自WHY42
Riguz讨论 | 贡献2023年12月19日 (二) 06:55的版本 (Riguz移动页面Java:ThreadLocalJava 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<?>>