Java ThreadLocal:修订间差异

来自WHY42
Riguz留言 | 贡献
建立內容為「= ThreadLocal原理 = 每个Thread中维护了一个<span class="article-label">ThreadLocal.ThreadLocalMap</span>的对象来存储: * 这个变量默认是null…」的新頁面
 
Riguz留言 | 贡献
第32行: 第32行:
     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
     ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
</syntaxhighlight>
</syntaxhighlight>
<q>
ThreadLocal instance does not keep but provides the access to thread-specific value using itself as a key.
</q>


= WeakReference =
= WeakReference =

2021年4月29日 (四) 09:37的版本

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<?>>