ThreadLocals

2020-08-10  本文已影响0人  说书的苏斯哈

一般都是从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();
    }

  • 获取当前线程t
  • 通过线程 t 获取ThreadLocalMap对象 map ,调用的是getMap(t) 方法
 ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

threadLocals是线程中的ThreadLocalMap对象,初始值是null

  • 这里针对map 是否为null 有两种情况

  • 首次进来的时候 map 是null

    进入到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;
        }
    
    • 首先通过initialValue()方法获取初始化的值

       protected T initialValue() {
              return null;
          }
      

      这个初始化的值为null

    • 然后调用getMap(t) 这个时候返回的也是null

    • 如果为null的话调用了createMap(t, value);

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

      在createMap中调用了ThreadLocalMap的构造方法,其中t就是当前线程的ThreadLocals对象,firstValue为null,创建的ThreadLocalMap对象赋值给了t线程中的threadLocals对象,这样在下次get的时候就获取到getMap()就不为null了

       ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
                  table = new Entry[INITIAL_CAPACITY];
                  int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
                  table[i] = new Entry(firstKey, firstValue);
                  size = 1;
                  setThreshold(INITIAL_CAPACITY);
              }
      
      
      1. 首先创建一个16大小的Entry数组
      2. 通过hashCode与(16-1)的与操作得出索引坐标i
      3. 新创建一个Entry对象放到数组的i坐标处
    • 首次进来的时候会创建一个ThreadLocalMaps,里面存放的值是null

  • Map 如果不为null时,一般走的是get()方法的下面的代码

     ```java
    

    if (map != null) {
    ThreadLocalMap.Entry e = map.getEntry(this);
    if (e != null) {
    @SuppressWarnings("unchecked")
    T result = (T)e.value;
    return result;
    }
    }
    ```

​ 这时候如果Entry不为null 就返回了Entry的value值,回溯到前面的逻辑,首次进来创建的是一个Entry对象其中value是null的,也就是说如果不设置值,这个get()返回的就是一个null,因此是使用get之前需要一个set()方法

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

ThreadLocals内存泄漏的问题

上一篇 下一篇

猜你喜欢

热点阅读