谈一谈ThreadLocal

ThreadLocal是什么

如果某个变量只为单独线程服务,不存在共享的场景,我们可以考虑将变量放在ThreadLocal里,ThreadLocal将变量和线程绑定。这样方便了使用,也规避了线程不安全因素。

ThreadLocal怎么使用

    /**
     * ThreadLocal存放数据
     * 父子线程不共享
     */
    public static void threadLocal(){
        // new threadlocal
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        // 设置变量
        threadLocal.set("aaa");

        Thread dawson = new Thread(()->{
            log.info("子线程尝试从threadlocal中获取数据:{}", threadLocal.get());
            log.info("do something...");
        });
        dawson.start();
        try {
            dawson.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("主线程从threadlocal中获取数据:{}", threadLocal.get());
    }

输出:

2020-04-05 13:35:28.002 [Thread-0] INFO  com.test.thread.ThreadLocalTest - 子线程尝试从threadlocal中获取数据:null
2020-04-05 13:35:28.010 [Thread-0] INFO  com.test.thread.ThreadLocalTest - do something...
2020-04-05 13:35:28.010 [main] INFO  com.test.thread.ThreadLocalTest - 主线程从threadlocal中获取数据:aaa

注意,子线程无法使用父线程的ThreadLocal中的数据。

InheritableThreadLocal的使用

在这里插入图片描述
InheritableThreadLocal 是ThreadLocal的子类,从名字来看含义为可继承的ThreadLocal,也就是子线程中也可以使用父线程设置的变量。

    /**
     * InheritableThreadLocal存放数据
     * 父子线程共享
     */
    public static void inheritableThreadLocal(){
        // 创建InheritableThreadLocal实例
        InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();
        // 向inheritableThreadLocal设置变量
        inheritableThreadLocal.set("aaa");
        Thread dawson = new Thread(()->{
            log.info("子线程尝试从inheritableThreadLocal中获取数据:{}", inheritableThreadLocal.get());
            log.info("do something...");
        });
        dawson.start();
        try {
            dawson.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("主线程从inheritableThreadLocal中获取数据:{}", inheritableThreadLocal.get());
    }

输出:

2020-04-05 13:34:31.704 [Thread-0] INFO  com.test.thread.ThreadLocalTest - 子线程尝试从inheritableThreadLocal中获取数据:aaa
2020-04-05 13:34:31.709 [Thread-0] INFO  com.test.thread.ThreadLocalTest - do something...
2020-04-05 13:34:31.710 [main] INFO  com.test.thread.ThreadLocalTest - 主线程从inheritableThreadLocal中获取数据:aaa

ThreadLocal原理

	// ThreadLocal源码

	// 向threadlocal设置数据
    public void set(T value) {
    	// 获取当前线程
        Thread t = Thread.currentThread();
        // 根据当前线程获取ThreadLocalMap(根据名字这应该是个hashmap结构),也就是每个线程都会有个这个结构
        ThreadLocalMap map = getMap(t);
        if (map != null)
        	// 这个map不为null,就设置数据
        	// !!注意这里的key为this,也就是threadlocal实例的引用 
            map.set(this, value);
        else
        	// 创建这个map结构
            createMap(t, value);
    }
    // 根据线程获取map结构
    ThreadLocalMap getMap(Thread t) {
    	// 这里直接返回的是线程的一个实例变量
        return t.threadLocals;
    }
    // 创建这个map结构
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

	// 从threadlocal获取数据
    public T get() {
    	// 获取当前线程,从当前线程的threadlocal中获取数据
        Thread t = Thread.currentThread();
        // 从当前线程中获取map结构
        ThreadLocalMap map = getMap(t);
        if (map != null) {
        	// 根据当前threadlocal的实例this来获取
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

以上就是大体上的调用关系,我们来看下Thread类中的那个实例变量threadLocals

	// 这是Thread的源码
	
    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    // 这就是在ThreadLocal中调用的那个线程的实例变量,这个变量又是ThreadLocal中定义的类型
    ThreadLocal.ThreadLocalMap threadLocals = null;

    /*
     * InheritableThreadLocal values pertaining to this thread. This map is
     * maintained by the InheritableThreadLocal class.
     */
     // 这里还有个类似的实例变量,根据名字猜测,就是上面我们说的可继承的threadlocal
    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

ok,我们又清楚了一些,然后画个图
在这里插入图片描述
我们分析出来步骤:
设置数据的流程

创建threadlocal对象t1
设置数据t1.set
获取当前线程
从线程中获取map结构
根据t1设置数据m.set

读取数据的流程

获取threadlocal对象t1
读取数据t1.get
获取当前线程
从线程中获取map结构
根据t1读取数据m.get

继续来看ThreadLocalMap结构,部分源码

	static class ThreadLocalMap {
		// 注意 这个Entry继承来弱引用
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
            	// 这里将key,也就是ThreadLocal实例的this传入父类
            	// 意味着,当key不存在其他强引用的情况下,再一次的gc会把k回收掉,如果回收掉后,value还存在,但是引用不到,就存在一定内存泄漏风险,如何规避?当key不用时,主动调用key的remove方法
                super(k);
                value = v;
            }
        }
        // 数组,用来做map结构,每个元素为Entry类型,该类型定义如上
        private Entry[] table;
        private void set(ThreadLocal<?> key, Object value) {
            Entry[] tab = table;
            int len = tab.length;
            // 计算key对应的数组下标,key是啥?就是this
            int i = key.threadLocalHashCode & (len-1);

            for (Entry e = tab[i];
                 e != null;
                 // 获取下标对应的元素
                 e = tab[i = nextIndex(i, len)]) {
                ThreadLocal<?> k = e.get();

                if (k == key) {
                // 如果该下标没有元素,设置数据
                    e.value = value;
                    return;
                }

                if (k == null) {
                    replaceStaleEntry(key, value, i);
                    return;
                }
            }

            tab[i] = new Entry(key, value);
            int sz = ++size;
            if (!cleanSomeSlots(i, sz) && sz >= threshold)
                rehash();
        }

内存泄漏风险

该原理已经在上述源码的解释中说明
参考:面试官:ThreadLocal为什么会发生内存泄漏
在这里插入图片描述
ThreadLocal的实现是这样的:每个Thread 维护一个 ThreadLocalMap 映射表,这个映射表的 key 是 ThreadLocal 实例本身,value 是真正需要存储的 Object。

也就是说 ThreadLocal 本身并不存储值,它只是作为一个 key 来让线程从 ThreadLocalMap 获取 value。值得注意的是图中的虚线,表示 ThreadLocalMap 是使用 ThreadLocal 的弱引用作为 Key 的,弱引用的对象在 GC 时会被回收。
ThreadLocalMap使用ThreadLocal的弱引用作为key,如果一个ThreadLocal没有外部强引用来引用它,那么系统 GC 的时候,这个ThreadLocal势必会被回收,这样一来,ThreadLocalMap中就会出现key为null的Entry,就没有办法访问这些key为null的Entry的value,如果当前线程再迟迟不结束的话,这些key为null的Entry的value就会一直存在一条强引用链:Thread Ref -> Thread -> ThreaLocalMap -> Entry -> value永远无法回收,造成内存泄漏。
最佳实践:每次使用完ThreadLocal,都调用它的remove()方法,清除数据。

InheritableThreadLocal怎么做到的继承?

查看Thread源码

	// 线程的构造方法
    public Thread() {
    	// 这里设置默认线程的名字,以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);
    }

    /**
     * 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. 
     * 所需栈大小,0为忽略
     * @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 
     * 是否从父线程中继承threadlocal
     */
    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);
        // 以下判断是否需要从父线程中继承treadlocal
        if (inheritThreadLocals && parent.inheritableThreadLocals != null)
        	// 如果继承,就设置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();
    }

上述源码所示,之所以能继承,是因为在创建线程时,直接把父线程的threadlocal复制到类当前线程。

源码中涉及到的弱引用

在JDK 1.2版之后,Java对引用的概念进行了扩充,将引用分为强引用(Strongly Re-ference)、软引用(Soft Reference)、弱引用(WeakReference)和虚引用(Phantom Reference)4种,这4种引用强度依次逐渐减弱。

强引用

强引用是最传统的“引用”的定义,是指在程序代码之中普遍存在的引用赋值,即类似“Object obj=new Object()”这种引用关系。无论任何情况下,只要强引用关系还存在,垃圾收集器就永远不会回收掉被引用的对象。

软引用

软引用是用来描述一些还有用,但非必须的对象。只被软引用关联着的对象,在系统将要发生内存溢出异常前,会把这些对象列进回收范围之中进行第二次回收,如果这次回收还没有足够的内存,才会抛出内存溢出异常。在JDK 1.2版之后提供了SoftReference类来实现软引用。

弱引用

弱引用也是用来描述那些非必须对象,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发生为止。当垃圾收集器开始工作,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。在JDK 1.2版之后提供了WeakReference类来实现弱引用。

虚引用

虚引用也称为“幽灵引用”或者“幻影引用”,它是最弱的一种引用关系。一个对象是否有虚引用的存在,完全不会对其生存时间构成影响,也无法通过虚引用来取得一个对象实例。为一个对象设置虚引用关联的唯一目的只是为了能在这个对象被收集器回收时收到一个系统通知。在JDK 1.2版之后提供了PhantomReference类来实现虚引用。
参考:深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值