Skip to content

thread local

wangkaiwu edited this page Feb 9, 2023 · 2 revisions

线程局部变量

  • jdk 版本
  • netty 版本

jdk 版本

初始化

public class Thread implements Runnable {
    ThreadLocal.ThreadLocalMap threadLocals = null;
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
}
public class ThreadLocal<T> {
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }
}

初始化或者赋值

public class ThreadLocal<T> {
    private T setInitialValue() {
        // 获取初始化的值
        T value = initialValue();
        Thread t = Thread.currentThread();
        // 获取局部变量的 map
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            // 此处是常规赋值
            map.set(this, value);
        } else {
            createMap(t, value);
        }
        return value;
    }
}
public class ThreadLocal<T> {
    static class ThreadLocalMap {
        private Entry[] table;
        private void set(ThreadLocal<?> key, Object value) {
            // table 的赋值
            Entry[] tab = table;
            int len = tab.length;
            // 在下面查看 threadLocalHashCode 的赋值
            int i = key.threadLocalHashCode & (len-1);
        }
    }
}

附录

table 赋值

public class ThreadLocal<T> {
    static class ThreadLocalMap {
        
    }
}

Clone this wiki locally