Java ThreadLocal:修订间差异

来自WHY42
Riguz留言 | 贡献
建立內容為「= ThreadLocal原理 = 每个Thread中维护了一个<span class="article-label">ThreadLocal.ThreadLocalMap</span>的对象来存储: * 这个变量默认是null…」的新頁面
 
Riguz留言 | 贡献
Riguz移动页面Java:ThreadLocalJava ThreadLocal,不留重定向
 
(未显示同一用户的1个中间版本)
第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 =

2023年12月19日 (二) 06:55的最新版本

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