InheritableThreadLocal父線程傳遞子線程線程安全

前言

       最近做項目,需要全鏈路跟蹤,有各種比較成熟的方案,MDC/NDC log方式;zipkin之類的框架。究其根源是ThreadLocal與InheritableThreadLocal。下面看看兩者的區別。

1. threadLocal demo

public class ThreadLocalDemo {

    static ThreadLocal<String> local = new ThreadLocal<String>(){
        @Override
        protected String initialValue() {
            return "super.initialValue()";
        }
    };

    public static void main(String[] args) {
        local.set("hello");
        
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        for (int i = 0; i < 10; i++) {
            executorService.submit(()->{
                System.out.println(local.get());
            });
        }

        System.out.println("shutdown----------------------");
        executorService.shutdown();
    }
}

運行結果

可以看到,當前線程main線程的threadlocal設置的值在線程池中未傳遞。追根溯源是

public class ThreadLocal<T> {
    public T get() {
        Thread t = Thread.currentThread();
        //此處子線程獲取爲null
        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();
    }

    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

2. InheritableThreadLocal demo

public class InheritableThreadLocalDemo {

    static InheritableThreadLocal<String> local = new InheritableThreadLocal<String>(){
        @Override
        protected String initialValue() {
            return "super.initialValue()";
        }
    };

    public static void main(String[] args) {
        local.set("hello");
        ExecutorService executorService = Executors.newFixedThreadPool(6);
        for (int i = 0; i < 10; i++) {
            executorService.submit(()->{
                System.out.println(local.get());
            });
        }

        System.out.println("shutdown----------------------");
        executorService.shutdown();
    }
}

運行結果

可以看到main線程設置的hello在子線程中傳遞過去了。下面來分析原因:

//本質還是threadlocal
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) {
        //返回parent的值
        return parentValue;
    }

    /**
     * Get the map associated with a ThreadLocal.
     *
     * @param t the current thread
     */
    ThreadLocalMap getMap(Thread t) {
       //存放在線程的inheritableThreadLocals
       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) {
        //初始化map,本質還是ThreadLocalMap
        t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
    }
}

沒看出來父子線程的threadlocal是如何傳遞的,那麼只能分析Thread的創建過程,查看new Thread()構造,其他構造函數本質同理。

可以看到,默認是需要 初始化 inheritThreadLocals的

只有一個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();
        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);
        //非常關鍵,如果父線程有inheritableThreadLocals ,子線程使用父線程的inheritableThreadLocals 初始化
        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();
    }

每次新建線程,用父線程的 inheritThreadLocals創建threadlocalmap

跟蹤

/**
         * Construct a new map including all Inheritable ThreadLocals
         * from given parent map. Called only by createInheritedMap.
         *
         * @param parentMap the map associated with parent thread.
         */
        private ThreadLocalMap(ThreadLocalMap parentMap) {
            Entry[] parentTable = parentMap.table;
            int len = parentTable.length;
            setThreshold(len);
            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) {
                        Object value = key.childValue(e.value);
                        Entry c = new Entry(key, value);
                        //計算槽位
                        int h = key.threadLocalHashCode & (len - 1);
                        //hash衝突,這裏算法重寫了,跟hashmap差異較大
                        while (table[h] != null)
                            //重算hash槽位
                            h = nextIndex(h, len);
                        table[h] = c;
                        size++;
                    }
                }
            }
        }

hash重寫了,沒有鏈表了。算法挺簡單,hash衝突,數組下標+1,估計設計之初就考慮到存儲的數據不大。

        /**
         * Increment i modulo len.
         */
        private static int nextIndex(int i, int len) {
            return ((i + 1 < len) ? i + 1 : 0);
        }

        /**
         * Decrement i modulo len.
         */
        private static int prevIndex(int i, int len) {
            return ((i - 1 >= 0) ? i - 1 : len - 1);
        }

threadlocalmap的hash計算非常有意思,原子類每次加固定值

總結

       ThreadLocal的值是不能從父線程傳遞到子線程的,如果僅需要每個線程一個threadlocal對象,沒有子線程的傳遞,threadlocal完全符合要求,如果需要在線程間傳遞就要InheritableThreadLocal,比如日誌跟蹤,全鏈路;它們的本質就是InheritableThreadLocal,因此在輕量級的處理時,日誌就可以做全鏈路跟蹤。配合Kibana或者grafana做展示。複雜的處理需要埋點,建設admin端增強控制能力。

 

 

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