Java ThreadLocal

ThreadLocal的作用是提供线程内局部变量,这种变量在线程生命周期内起作用。

ThreadLocal.set()

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

Thread

    ThreadLocal.ThreadLocalMap threadLocals = null;

ThreadLocal.set()通过对应的线程Thread获取Thread成员变量threadLocals。threadLocals是ThreadLocal的内部类ThreadLocalMap。map为null,创建ThreadLocalMap并给赋值给Thread的成员变量threadLocals。然后调用map.set(this, value),这里this--->ThreadLocal。

ThreadLocalMap.set()

        private void set(ThreadLocal key, Object value) {
            Entry[] tab = table;
            int len = tab.length;
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal k = e.get();

                if (k == key) {
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

ThreadLocalMap很明显是个map。这里不纠结其具体实现,只需知道map的key是ThreadLocal对象,value是set()的值。

ThreadLocal.get()

    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();
    }

    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

    protected T initialValue() {
        return null;
    }

get()方法从ThreadLocalMap中取值

  • ThreadLocal通过其内部类ThreadLocalMap来维护变量值。
  • ThreadLocalMap存储在Thread对象中。
  • ThreadLocalMap的key是ThreadLocal对象,value是变量值。

你可能感兴趣的:(Java ThreadLocal)