在Java并发编程中,InheritableThreadLocal 与 ThreadLocal 都可以用于线程间通信,不同的是 InheritableThreadLocal 继承了 ThreadLocal,并且扩展了 ThreadLocal。使用类 InheritableThreadLocal 可使子线程继承父线程的值。相反,类 ThreadLocal 不能实现值继承。

使用示例:

public class LocalThread extends Thread {
    private static InheritableThreadLocal local = new InheritableThreadLocal();

    @Override
    public void run() {
        System.out.println("thread线程:"+ local.get());
    }

    public static void main(String[] args) throws InterruptedException {
        local.set("main的值");
        LocalThread t = new LocalThread();
        t.start();
        System.out.println("main线程:"+ local.get());
    }

}

如果想要自定义 get() 方法默认值,具体操作也和 ThreadLocal 是一样的。

public class Local extends InheritableThreadLocal {

    @Override
    protected Object initialValue() {
        return new Date();
    }
}

InheritableThreadLocal 提供继承的同时还可以进行进一步的处理。代码如下:

public class Local extends InheritableThreadLocal {

    @Override
    protected Object initialValue() {
        return new Date();
    }

    @Override
    protected Object childValue(Object parentValue) {
        return parentValue+"[子线程增强版]";
    }
}

分析下 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);
    }
}

可以看到,getMap() 方法和 creatMap() 方法都是重写的 ThreadLocal 类方法,区别在于把 ThreadLocal 中的 threadLocals 换成了 inheritableThreadLocals,这两个变量都是ThreadLocalMap类型,并且都是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;

inheritableThreadLocal 如何实现值继承的呢?继续看下面的代码:

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

在构造方法的完整源代码算法中可以发现,子线程将父线程中的 table 对象以复制的方式赋值给子线程的 table 数组,这个过程是在创建 Thread 类对象时发生的,也就说明当子线程对象创建完毕后,子线程中的数据就是主线程中旧的数据,主线程使用新的数据时,子线程还是使用旧的数据,因为主子线程使用两个 Entry[] 对象数组各自存储自己的值。

这部分涉及到 Java 的值传递。对于对象来说,值的内容其实是对象的引用。当在父线程中修改对象的某一属性,子线程由于引用着相同对象,所以可以感知到,本质上是在操作同一块内存地址。

对于基本数据类型(int、long)来说,由于传递的是值,在父线程改变了数据后,子线程依旧使用的是旧的数据。这里尤其要提 String 字符串,String 虽然不是基本数据类型,但是由于内部字符数组被 final 修饰带来的不可变型,当父线程修改其 String 类型数据时,等于替换掉该 String 对象,而并不是修改原 String 对象的值,所以子线程依旧不会发生变化。

另外,重写类 InheritableThreadLocal 的 childValue() 方法可以对继承的值进行加工,比如通过调用clone() 方法返回 parentValue 的浅拷贝,以达到子线程无法影响父线程的目的。

详解InheritableThreadLocal类的使用与原理的更多相关文章

  1. 并发编程之详解InheritableThreadLocal类原理

    [本文版权归微信公众号"代码艺术"(ID:onblog)所有,若是转载请务必保留本段原创声明,违者必究.若是文章有不足之处,欢迎关注微信公众号私信与我进行交流!] 在Java并发编 ...

  2. Python进阶——详解元类,metaclass的原理和用法

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是Python专题第18篇文章,我们来继续聊聊Python当中的元类. 在上上篇文章当中我们介绍了type元类的用法,在上一篇文章当中我 ...

  3. RocketMQ详解(四)核心设计原理

    专题目录 RocketMQ详解(一)原理概览 RocketMQ详解(二)安装使用详解 RocketMQ详解(三)启动运行原理 RocketMQ详解(四)核心设计原理 RocketMQ详解(五)总结提高 ...

  4. unity3D游戏开发之详解Animation类和Animator类

    详解Animator类和Animation类 链接: http://wenku.baidu.com/link?url=SiaUYcdrNYjOYrWVDJSKGAYdJOntMTOhsVJtyBk2i ...

  5. 【python进阶】详解元类及其应用1

    前言 元类在python中是很重要的一部分,我将分两次去讲解元类及其应用,此篇为详解元类及其应用第一篇,下面开始今天的说明~~~ 1. 类也是对象 在⼤多数编程语⾔中,类就是⼀组⽤来描述如何⽣成⼀个对 ...

  6. 【python进阶】详解元类及其应用2

    前言 在上一篇文章[python进阶]详解元类及其应用1中,我们提到了关于元类的一些前置知识,介绍了类对象,动态创建类,使用type创建类,这一节我们将继续接着上文来讲~~~ 5.使⽤type创建带有 ...

  7. Unity3D - 详解Quaternion类(二)

    OK,不做引子了,接上篇Unity3D - 详解Quaternion类(一)走起! 四.Quaternion类静态方法 Quaternion中的静态方法有9个即:Angle方法.Dot方法.Euler ...

  8. Unity3D - 详解Quaternion类(一)

    一.简介 Quaternion又称四元数,由x,y,z和w这四个分量组成,是由爱尔兰数学家威廉·卢云·哈密顿在1843年发现的数学概念.四元数的乘法不符合交换律.从明确地角度而言,四元数是复数的不可交 ...

  9. Java网络编程和NIO详解6:Linux epoll实现原理详解

    Java网络编程和NIO详解6:Linux epoll实现原理详解 本系列文章首发于我的个人博客:https://h2pl.github.io/ 欢迎阅览我的CSDN专栏:Java网络编程和NIO h ...

随机推荐

  1. Java学习笔记之---方法和数组

    Java学习笔记之---方法与数组 (一)方法 (1)什么是方法? 方法是解决一类问题的步骤的有序组合 方法包含于类或对象中 方法在程序中被创建,在其他地方被引用 (2)方法的优点 使程序变得更简短而 ...

  2. spring boot admin抛出"status":401,"error":"Unauthorized"异常

    打开spring boot admin的监控平台发现其监控的服务明细打开均抛出异常: Error: {"timestamp":1502749349892,"status& ...

  3. webpack-dev-server 小记 原理介绍 概念解读

    使用 DevServer 提供 HTTP 服务而不是使用本地文件预览 监听文件的变化并自动刷新网页,做到实时预览 支持 Source Map,以方便调试 对于这些,Webpack 都为我们考虑好了.W ...

  4. py+selenium 直接给日期赋值,控制台调试报错【已解决】

    目标:给带日期控件的输入框赋值. 百度去搜索让你各种去只读readonly属性,再send_keys 方法: 其实既然可以去除readonly属性,那就可以直接给属性赋值,将两行代码缩为一行. dri ...

  5. Oracle 开发使用笔记一

    1 前段时间换了新公司,工作一直很忙,没什么时间做总结! 关于几个知识点简单做下总结: 1绑定变量的使用: 1)使用几次,在后面的using中要声明几次,使用的顺序要对应声明的顺序 2 存储过程中执行 ...

  6. Baozi Leetcode Solution 205: Isomorphic Strings

    Problem Statement Given two strings s and t, determine if they are isomorphic. Two strings are isomo ...

  7. Java、Java SE、Java Web和Java EE的区别

    刚接触Java对这些概念上的东西有点模糊,查了很多资料,想把它分享出来,要是哪里不对请大家指正(^_^) 1.Java 毫无疑问这就是门语言和C.C++.C#一样没什么好说的. 2.Java SE和J ...

  8. HTML页面中的布局问题

    在做网站中,给整个大的框架宽度设置为100%,然后设置body的最小宽度是网站的内容部分的宽度.网站内容的宽度是固定的.

  9. 10G文件如何对里面单词出现排序

    10G文件如何对里面单词出现排序的问题(只要文件系统支持,不限大小). 其实这个问题很简单,10G文件是很大,但是出现的字符或单词是很有限的. 单字符只有那么一百多个,单词数量满打满算,以英文单词总数 ...

  10. ASP.NET Core Web Api之JWT VS Session VS Cookie(二)

    前言 本文我们来探讨下JWT VS Session的问题,这个问题本没有过多的去思考,看到评论讨论太激烈,就花了一点时间去研究和总结,顺便说一句,这就是写博客的好处,一篇博客写出有的可能是经验积累,有 ...