ThreadLocal父子線程傳遞的坑

在這裏插入圖片描述

前言

如果子線程想要拿到父線程的中的ThreadLocal值怎麼辦呢?看下下面代碼


public class ThreadLocalParentChild {

    public static void main(String[] args) {

        final ThreadLocal threadLocal = new ThreadLocal() {
            @Override
            protected Object initialValue() {
                return "abc";
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(threadLocal.get());//NULL
            }
        }).start();
    }

}

子線程獲取的時候會使null,這個問題InheritableThreadLocal已經幫我們解決了

InheritableThreadLocal

把ThreadLocal換成InheritableThreadLocal,發現問題已經解決了。


public class InheritableThreadLocalParentChild {

    public static void main(String[] args) {

        final InheritableThreadLocal threadLocal = new InheritableThreadLocal() {
            @Override
            protected Object initialValue() {
                return "abc";
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(threadLocal.get());
            }
        }).start();
    }

}

可以看到輸出的是abc,下面來看下它的源碼


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

可以看到重寫了getMap和createMap方法,inheritableThreadLocals這個變量是一個新的變量,記得ThreadLocal裏面用的是threadLocals,這兩個變量都是Thread中的變量,我們可以看下JDK都幹了什麼事。

下面是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;

確實是兩個變量,那就有個問題,子線程是如何拿到父線程中的變量的呢?

我們在new Thread的時候看都做什麼,一步一步來


    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }

     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();
        if (g == null) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }

        g.addUnstarted();

        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        //inheritThreadLocals=true,上面傳過來的,如果父線程的inheritableThreadLocals不爲null,就淺拷貝一份
        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();
    }

一步一步的調用,最終到了init方法上,如果父線程的inheritableThreadLocals不爲null,就淺拷貝一份給當前線程,所以子線程就可以拿到父線程的值了。但是這樣就不會有問題了麼,我們真正開發的時候用的是線程池,我們來試下


public class ThreadPoolInheritable {

    public static void main(String[] args) throws InterruptedException {
        final InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal();
        inheritableThreadLocal.set("aaa");
        //輸出 aaa
        System.out.println(inheritableThreadLocal.get());

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("========");
                System.out.println(inheritableThreadLocal.get());
                inheritableThreadLocal.set("bbb");
                System.out.println(inheritableThreadLocal.get());
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        executorService.submit(runnable);
        TimeUnit.SECONDS.sleep(1);
        executorService.submit(runnable);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("========");
        System.out.println(inheritableThreadLocal.get());
    }

}

aaa
========
aaa
bbb
========
bbb
bbb
========
aaa

線程池運行了兩次,看第二次的結果,我們拿到的數據都是bbb了,這就有問題了,這就說明線程池裏面的線程是緩存的,線程結束後,沒有清除ThreadLocalMap中的內容,下次這個再次提交任務的時候,取得還是線程池中緩存的線程,輸出的還是上次的ThreadLocalMap中的內容,於是就出現了拿父線程的ThreadLocal變量就錯了。

面對這種問題,經過搜索阿里transmittable-thread-local可以解決

transmittable-thread-local

github地址: https://github.com/alibaba/transmittable-thread-local

看了阿里的解決方案之後,我們再來試下

首先得引入pom

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>transmittable-thread-local</artifactId>
            <version>2.6.1</version>
        </dependency>

再來看下測試代碼


public class ThreadPoolTransmittable {

    public static void main(String[] args) throws InterruptedException {
        final TransmittableThreadLocal transmittableThreadLocal = new TransmittableThreadLocal();
        transmittableThreadLocal.set("aaa");
        //輸出 aaa
        System.out.println(transmittableThreadLocal.get());

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("========");
                System.out.println(transmittableThreadLocal.get());
                transmittableThreadLocal.set("bbb");
                System.out.println(transmittableThreadLocal.get());
            }
        };

        ExecutorService executorService = Executors.newFixedThreadPool(1);
        ExecutorService ttlExecutorService = TtlExecutors.getTtlExecutorService(executorService);
        ttlExecutorService.submit(runnable);
        TimeUnit.SECONDS.sleep(1);
        ttlExecutorService.submit(runnable);
        TimeUnit.SECONDS.sleep(1);
        System.out.println("========");
        System.out.println(transmittableThreadLocal.get());
    }
}

aaa
========
aaa
bbb
========
aaa
bbb
========
aaa

可以看到第二次任務先輸出aaa,在輸出bbb是我們想要的結果。

它的原理其實就是線程執行之前進行復制父線程的線程變量,線程結束之後清楚了父線程線程變量。說的比較籠統,如果有更好的解釋,歡迎下方評論。

總結

開發過程中,我們用阿里的還是比較多的,推薦這種用法,最後看了官方文檔,看到了使用了java agent技術,這個東西調研下,準備在下篇文章輸出。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章