美文网首页工作生活
ThreadLocal的继承性该如何实现

ThreadLocal的继承性该如何实现

作者: 孤独而无用 | 来源:发表于2019-07-04 20:46 被阅读0次

    开发过程中发现,同一个ThreadLocal变量在父线程中被设置值后,在子线程中是获取不到的,经过查询学习,发现有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继承了ThreadLocal,并重写了3个方法.
    createMap被重写,当第一次调用set方法的时候,创建的是当前线程的inheritableThreadLocals 变量的实例而不再是ThreadLocals.
    get方法也是同样.

    我们看下childValue(T parentValue)何时被执行,以及如何让子线程可以访问父线程的本地变量. 打开Thread类的默认构造函数,代码如下:

        /**
         * Initializes a Thread with the current AccessControlContext.
         * @see #init(ThreadGroup,Runnable,String,long,AccessControlContext,boolean)
         */
        private void init(ThreadGroup g, Runnable target, String name,
                          long stackSize) {
            init(g, target, name, stackSize, null, true);
        }
    
        /**
         * Initializes a Thread.
         *
         * @param g the Thread group
         * @param target the object whose run() method gets called
         * @param name the name of the new Thread
         * @param stackSize the desired stack size for the new thread, or
         *        zero to indicate that this parameter is to be ignored.
         * @param acc the AccessControlContext to inherit, or
         *            AccessController.getContext() if null
         * @param inheritThreadLocals if {@code true}, inherit initial values for
         *            inheritable thread-locals from the constructing thread
         */
        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);
            // (1)如果父线程的inheritableThreadLocals 不为null
            if (inheritThreadLocals && parent.inheritableThreadLocals != null)
            // (2)设置子线程中的inheritableThreadLocals 变量
                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方法
    Thread parent = currentThread();获取了当前线程(这里指main函数所在线程,也就是父线程),然后(1)判断了父线程的属性输不是null,如果不是null则会执行代码(2)

    static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
            return new ThreadLocalMap(parentMap);
        }
    

    可以看到, 在createInheritedMap内部使用父线程的inheritableThreadLocals变量作为构造函数创建了一个新的ThreadLocalMap变量,然后赋值给了子线程的inheritableThreadLocals变量,下面我们看下在ThreadLocalMap构造函数内部做了些什么:

     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);
                            while (table[h] != null)
                                h = nextIndex(h, len);
                            table[h] = c;
                            size++;
                        }
                    }
                }
            }
    

    在该构造函数内部把父线程的inheritableThreadLocals成员变量的值复制到新的ThreadLocalMap对象中.其中Object value = key.childValue(e.value);调用了inheritableThreadLocal类重写的方法.

    这种办法对中间件需要把统一的id追踪的整个调用链路记录下来很有好处, 我觉得大众点评的cat可能就是这么做的,虽然我还没有研究.

    与君共勉...

    相关文章

      网友评论

        本文标题:ThreadLocal的继承性该如何实现

        本文链接:https://www.haomeiwen.com/subject/cnldhctx.html