https://cloud.tencent.com/developer/article/1162226

前言

介绍InheritableThreadLocal之前,假设读者对 ThreadLocal 已经有了一定的理解,比如基本概念、原理等。在讲解之前我们先列举有关ThreadLocal的几个关键点。

每一个Thread线程都有属于自己的ThreadLocalMap,里面有一个弱引用的Entry(ThreadLocal,Object),如下:

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

从ThreadLocal中get值的时候,首先通过Thread.currentThread得到当前线程,然后拿到这个线程的ThreadLocalMap。再传递当前ThreadLocal对象(结合上一点),取得Entry中的value值。

set值的时候同理,更改的是当前线程的ThreadLocalMap的Entry中key为当前Threadlocal对象的value值。

Threadlocal bug?

如果子线程想要拿到父线程的中的ThreadLocal值怎么办呢?比如会有以下的这种代码的实现。由于ThreadLocal的实现机制,在子线程中调用get时,我们拿到的Thread对象是当前子线程对象,那么他的ThreadLocalMap是null的,所以我们得到的value也是null。(注:原文举的例子有错误,沉思君重写了示例代码)

public class ThreadLocalTest {

    public static void main(String[] args) throws  Exception{
        final ThreadLocal<String> threadLocal=new ThreadLocal<String>();
        threadLocal.set("Java架构沉思录");
        System.out.println("父线程的值:"+threadLocal.get());
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("子线程的值:"+threadLocal.get());
            }
        }).start();

        Thread.sleep(2000);
    }
}

结果输出如下:

https://ask.qcloudimg.com/http-save/yehe-1346475/6psqehbjk2.png

InheritableThreadLocal实现

那其实很多时候我们是有子线程获得父线程ThreadLocal的需求的,要如何解决这个问题呢?这就是InheritableThreadLocal这个类所做的事情。先来看下InheritableThreadLocal所做的事情。

public class InheritableThreadLocal<T> extends ThreadLocal<T> {
    /**
     * Computes the child's initial value for this inheritable thread-local
     * variable as a function of the parent's value at the time the child
     * thread is created.  This method is called from within the parent
     * thread before the child is started.
     * <p>
     * This method merely returns its input argument, and should be overridden
     * if a different behavior is desired.
     *
     * @param parentValue the parent thread's value
     * @return the child thread's initial value
     */
    protected T childValue(T parentValue) {
        return parentValue;
    }

    /**
     * Get the map associated with a ThreadLocal.
     *
     * @param t the current thread
     */
    ThreadLocalMap getMap(Thread t) {
       return t.inheritableThreadLocals;
    }

    /**
     * Create the map associated with a ThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the table.
     */
    void createMap(Thread t, T firstValue) {
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

以上代码大致的意思就是,如果你使用InheritableThreadLocal,那么保存的所有东西都已经不在原来的t.thradLocals里面,而是在一个新的t.inheritableThreadLocals变量中了。下面是Thread类中两个变量的定义。

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

Q:InheritableThreadLocal是如何实现在子线程中能拿到当前父线程中的值的呢?

A:一个常见的想法就是把父线程的所有的值都copy到子线程中。