ThreadLocal代码片段梳理-浅析

测试代码

以jdk1.8的源码为例
测试代码

public static void main(String[] args) {  
    final ThreadLocal<Boolean> threadLocal = new ThreadLocal<Boolean>();  
    new Thread(new Runnable() {  
        @Override  
        public void run() {  
           threadLocal.set(true);  
           System.out.println("1 " + threadLocal.get());  
        }  
    }).start();
    new Thread(new Runnable() {  
        @Override  
        public void run() {  
           threadLocal.set(false);  
           System.out.println("2 " + threadLocal.get());  
        }  
    }).start();
    System.out.println("3 " + threadLocal.get());
}

输出结果

Thread 3 null
Thread 1 true
Thread 2 false

每个线程维护着自己的一个ThreadLocalMap,所以ThreadLocal对象,在不同线程中拥有不同的值。

ThreadLocalMap map = getMap(t);

主要涉及类Thread、ThreadLocalMap、ThreadLocalMap.Entry
代码片段如下:

1.set方法

ThreadLocal-泛型类

public class ThreadLocal<T> {

    public void set(T value) {
        //返回当前线程对象引用,调用了底层native方法  
        Thread t = Thread.currentThread();
        //获取Thread绑定的ThreadLocalMap对象  
        ThreadLocalMap map = getMap(t);  
        if (map != null)//当前ThreadLocalMap对象存在,则设置对应值  
            map.set(this, value);  
        else  
            createMap(t, value);//ThreadLocalMap对象不存在则创建  
    }

    /**  
     * Get the map associated with a ThreadLocal. Overridden in 
     * InheritableThreadLocal. 
     * @param t the current thread  
     * @return the map  
     */
    ThreadLocalMap getMap(Thread t) {  
        return t.threadLocals;  //threadLocals为thread的一个全局变量
    }
}

Thread

public class Thread implements Runnable {
    ...
    /** 
     *ThreadLocal values pertaining to this thread. This map is maintained  
     * by the ThreadLocal class. 
     */
     ThreadLocal.ThreadLocalMap threadLocals = null;
 }

1.第一次调用set方法时,ThreadLocalMap为空,所以执行createMap(t, value)

void createMap(Thread t, T firstValue) {
    //当前线程与ThreadLocalMap关联起来
    t.threadLocals = new ThreadLocalMap(this, firstValue);  
}

ThreadLocalMap

static class ThreadLocalMap {
    ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
        //初始化长度为16的一个Entry数组,INITIAL_CAPACITY默认为16二进制的10000  
        table = new Entry[INITIAL_CAPACITY];
        //根据ThreadLocal的hash值和1111做与操作,计算出table的下标值
        int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
        //存储ThreadLocal及泛型T值  
        table[i] = new Entry(firstKey, firstValue);       
        size = 1;  
        setThreshold(INITIAL_CAPACITY);  
    }
}

ThreadLocalMap.Entry

static class Entry extends WeakReference<ThreadLocal<?>> {  
    /** The value associated with this ThreadLocal. */  
    Object value;  

    Entry(ThreadLocal<?> k, Object v) {  
        super(k);  
        value = v;  
    }  
}

2.ThreadLocalMap不为空时,调用ThreadLocalMap.set(this, value);

private void set(ThreadLocal<?> key, Object value) {    
 // We don't use a fast path as with get() because it is at  
 // least as common to use set() to create new entries as 
 // it is to replace existing ones, in which case, a fast 
 // path would fail more often than not.  
 Entry[] tab = table;  
 int len = tab.length;  
 int i = key.threadLocalHashCode & (len-1);//测试过程中,下标为3

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

2.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;  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值