InheritableThreadLocal 解析

InheritableThreadLocal 继承自ThreadLocal,重写了childValue、getMap、createMap 方法,主要作用是子线程能够读取父线程的变量 看下这个类

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    protected T childValue(T parentValue) {
        return parentValue;
    }

    //返回的是Thread类的inheritableThreadLocals,而ThreadLocal使用的是threadLocals变量
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

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

示例:

public class InheritableThreadLocalTest {
    private static final InheritableThreadLocal<String> threadLocal = new InheritableThreadLocal<String> ();
    public static void main(String [] args) throws InterruptedException {
        threadLocal.set("hello world");
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //threadLocal.set("son thread");
                System.out.println("thread:" + threadLocal.get());
            }
        });

        thread.start();
        thread.join();
        System.out.println("main:" + threadLocal.get());
    }
}

输出:

thread:hello world
main:hello world

这里如果我在子线程中set了一个新值,那结果会怎么样? 发现父线程的值没有改变

thread:son thread
main:hello world
源码剖析
  1. 首先从新建子线程开始分析,这里主要就是将父线程的值copy到子线程中
//构造函数
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}

//直接跳到,最终的init方法
private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
    if (name == null) {
        throw new NullPointerException("name cannot be null");
    }

    this.name = name;

    Thread parent = currentThread();
    SecurityManager security = System.getSecurityManager();
    //....省略中间部分,看主要的
    //获取父线程的inheritableThreadLocals变量,如果不为空就copy父线程中的变量到子线程
    if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals =
            ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
    /* Stash the specified stack size in case the VM cares */
    this.stackSize = stackSize;

    /* Set thread ID */
    tid = nextThreadID();
}

//ThreadLocal.createInheritedMap方法
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
    return new ThreadLocalMap(parentMap);
}
    
//ThreadLocalMap(parentMap) 方法
private ThreadLocalMap(ThreadLocalMap parentMap) {
    Entry[] parentTable = parentMap.table;
    int len = parentTable.length;
    setThreshold(len);
    //新建一个Entry数组,Entry继承了WeakReference,key为ThreadLocal类型
    //这是为了在大数据量的时候,方便GC来回收已经失效的数据
    table = new Entry[len];

    for (int j = 0; j < len; j++) {
        Entry e = parentTable[j];
        if (e != null) {
            @SuppressWarnings("unchecked")
            ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
            if (key != null) {
                //InheritableThreadLocal 重写了childValue,返回value值
                Object value = key.childValue(e.value);
                Entry c = new Entry(key, value);
                //计算数组索引位置,使用"线性探测法"
                int h = key.threadLocalHashCode & (len - 1);
                //如果当前位置有值,指针需要移到下一个位置,直到找到不为null的位置
                while (table[h] != null)
                    h = nextIndex(h, len);
                table[h] = c;
                size++;
            }
        }
    }
}
  1. 子线程获取父线程值分析,看ThreadLocal的get方法
public T get() {
    Thread t = Thread.currentThread();
    //实际调用InheritableThreadLocal类getMap方法,getMap返回的是当前线程的inheritableThreadLocals变量
    //每个线程都有,是Thread类的局部变量
    ThreadLocalMap map = getMap(t);
    //如果是null会初始化一个value为null的ThreadLocalMap
    if (map != null) {
       //this就是InheritableThreadLocal类,看下getEntry方法
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) {
            @SuppressWarnings("unchecked")
            T result = (T)e.value;
            return result;
        }
    }
    return setInitialValue();
}
//这里就是从table数组中去获取索引对应的值,这个table已经在new Thread的时候copy了父线程的数据
private Entry getEntry(ThreadLocal<?> key) {
    int i = key.threadLocalHashCode & (table.length - 1);
    Entry e = table[i];
    if (e != null && e.get() == key)
        return e;
    else
        //如果条件不成立,会循环整个table,并处理key失效的数据
        //如果遍历完还没找到,就返回null
        return getEntryAfterMiss(key, i, e);
}
总结
  1. 子线程能够读取父线程数据,实际原因是新建子线程的时候,会从父线程copy数据
  2. InheritableThreadLocal 继承了ThreadLocal,并重写childValue、getMap、createMap,对该类的操作实际上是对线程ThreadLocalMap的操作

其他文章阅读:
ThreadLocal源码分析

转载于:https://my.oschina.net/itsaysay/blog/3095843

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值