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端增强控制能力。

 

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值