• 简单聊聊ThreadLocal吧


    1、聊聊ThreadLocal
    1.1、啥是ThreadLocal、是什么?

    ThreadLocal提供线程局部变量。这些变量与正常的变量不同,因为每一个线程在访问ThreadLocal实例的时候(通过其get或set方法)都有自己的、独立初始化的变量副本。ThreadLocal实例通常是类中的私有静态字段,使用它的目的是希望将状态(例如,用户ID或事务ID)与线程关联起来。

    ThreadLocal,也叫做线程本地变量或者线程本地存储

    1.2、作用何在?

    实现每一个线程都有自己专属的本地变量副本,主要解决了让每个线程绑定自己的值,通过使用get()和set()方法,获取默认值或将其值更改为当前线程所存的副本的值从而避免了线程安全问题

    1.3、Thread,ThreadLocal,ThreadLocalMap 关系

    在这里插入图片描述

    每个Thread都有一份threadLocal,threadLocalMap实际上就是一个以threadLocal实例为key任意对象为value的Entry对象。当我们为threadLocal变量赋值,实际上就是以当前threadLocal实例为key,值为value的Entry往这个threadLocalMap中存放。

    ThreadLocalMap从字面上就可以看出这是一个保存ThreadLocal对象的map(其实是以ThreadLocal为Key),不过是经过了两层包装的ThreadLocal对象:JVM内部维护了一个线程版的Map(通过ThreadLocal对象的set方法,结果把ThreadLocal对象自己当做key,放进了ThreadLoalMap中),每个线程要用到这个T的时候,用当前的线程去Map里面获取,通过这样让每个线程都拥有了自己独立的变量,人手一份,竞争条件被彻底消除,在并发模式下是绝对安全的变量。

    1.4、ThreadLocal内存泄露问题

    原因在于ThreadLocalMap继承了WeakReference(弱引用)。

    • 强引用:当内存不足,JVM开始垃圾回收,对于强引用的对象,就算是出现了OOM也不会对该对象进行回收,死都不收(java当中最常见的)除非赋值为null

    • 软引用:当内存不足时,就会回收被引用的对象,内存足时,不会被回收

    • 弱引用:垃圾回收器开始工作就会回收,只要jvm开始gc(回收) 就会被回收

    • 虚引用:最弱的引用,随时都有可能被回收

    内存泄漏:不再会被使用的对象或者变量占用的内存不能被回收,就是内存泄露

    		static class ThreadLocalMap {
    		        /**
    		         * The entries in this hash map extend WeakReference, using
    		         * its main ref field as the key (which is always a
    		         * ThreadLocal object).  Note that null keys (i.e. entry.get()
    		         * == null) mean that the key is no longer referenced, so the
    		         * entry can be expunged from table.  Such entries are referred to
    		         * as "stale entries" in the code that follows.
    		         */
    		        static class Entry extends WeakReference<ThreadLocal<?>> {
    		            /** The value associated with this ThreadLocal. */
    		            Object value;
    		
    		            Entry(ThreadLocal<?> k, Object v) {
    		                super(k);
    		                value = v;
    		            }
    		 }
     		/**
             * Remove the entry for key.
             */
            private void remove(ThreadLocal<?> key) {
                Entry[] tab = table;
                int len = tab.length;
                int i = key.threadLocalHashCode & (len-1);
                for (Entry e = tab[i];
                     e != null;
                     e = tab[i = nextIndex(i, len)]) {
                    if (e.get() == key) {
                        e.clear();
                        expungeStaleEntry(i);
                        return;
                    }
                }
            }
            /**
             * Get the entry associated with key.  This method
             * itself handles only the fast path: a direct hit of existing
             * key. It otherwise relays to getEntryAfterMiss.  This is
             * designed to maximize performance for direct hits, in part
             * by making this method readily inlinable.
             *
             * @param  key the thread local object
             * @return the entry associated with key, or null if no such
             */
            private Entry getEntry(ThreadLocal<?> key) {
                int i = key.threadLocalHashCode & (table.length - 1);
                Entry e = table[i];
                if (e != null && e.get() == key)
                    return e;
                else
                    return getEntryAfterMiss(key, i, e);
            }
            /**
             * Version of getEntry method for use when key is not found in
             * its direct hash slot.
             *
             * @param  key the thread local object
             * @param  i the table index for key's hash code
             * @param  e the entry at table[i]
             * @return the entry associated with key, or null if no such
             */
            private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
                Entry[] tab = table;
                int len = tab.length;
    
                while (e != null) {
                    ThreadLocal<?> k = e.get();
                    if (k == key)
                        return e;
                    if (k == null)
                        expungeStaleEntry(i);
                    else
                        i = nextIndex(i, len);
                    e = tab[i];
                }
                return null;
            }
    
            /**
             * Set the value associated with key.
             *
             * @param key the thread local object
             * @param value the value to be set
             */
            private void set(ThreadLocal<?> key, Object value) {
    
                // We don't use a fast path as with get() because it is at
                // least as common to use set() to create new entries as
                // it is to replace existing ones, in which case, a fast
                // path would fail more often than not.
    
                Entry[] tab = table;
                int len = tab.length;
                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();
            }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117

    既然弱引用引发内存泄漏问题,我们为啥还要用?
    当functione1方法执行完毕后,栈帧销毁强引用tl也就没有了。但此时线程的ThreadLocalMap里某个entry的key引用还指向这个对象

    若这个key引用是强引用,就会导致key指向的ThreadLocal对象v指向的对象不能被gc回收,造成内存泄漏;

    若这个key引用是弱引用大概率会减少内存泄漏的问题(还有一个key为null的坑)。使用弱引用,就可以使ThreadLocal对象在方法执行完毕后顺利被回收且Entry的key引用指向为null

    从前面的set,getEntry,remove方法看出,在threadLocal的生命周期里,针对threadLocal存在的内存泄漏的问题,都会通过expungeStaleEntry,cleanSomeSlots,replaceStaleEntry这三个方法清理掉key为null的脏entry。

    1.5、总结
    • ThreadLocal 并不解决线程间共享数据的问题

    • ThreadLocal 适用于变量在线程间隔离且在方法间共享的场景

    • ThreadLocal 通过隐式的在不同线程内创建独立实例副本避免了实例线程安全的问题

    • 每个线程持有一个只属于自己的专属Map并维护了ThreadLocal对象与具体实例的映射,该Map由于只被持有它的线程访问,故不存在线程安全以及锁的问题

    • ThreadLocalMap的Entry对ThreadLocal的引用为弱引用,避免了ThreadLocal对象无法被回收的问题

    • 都会通过expungeStaleEntry,cleanSomeSlots,replaceStaleEntry这三个方法回收键为 null 的 Entry 对象的值(即为具体实例)以及 Entry 对象本身从而防止内存泄漏,属于安全加固的方法

    • 每个Thread对象维护着一个ThreadLocalMap的引用

    • ThreadLocalMap是ThreadLocal的内部类,用Entry来进行存储

    • 调用ThreadLocal的set()方法时,实际就是往ThreadLocalMap设置值,key是ThreadLocal对象,值Value是传递进来的对象

    • 调用ThreadLocal的get()方法时,实际上就是往ThreadLocalMap获取值,key是ThreadLocal对象

    • ThreadLocal本身并不存储值,它只是自己作为一个key来让线程从ThreadLocalMap获取value,正因为这个原理,所有ThreadLocal能够实现数据隔离,获取当前对象的局部变量值,不受其他线程影响。

    在使用ThreadLocal的时候在线程池的情况下,必需回收自定义的ThreadLocal变量,尽量在try-finally快进行回收。

  • 相关阅读:
    TDengine函数大全-系统函数
    Apache Jmeter BeanShell 实现跨文件跨线程全自动获取Token并写入CSV文件
    学习教授LLM逻辑推理11.19
    软件工程毕业设计课题(65)微信小程序毕业设计PHP食堂餐厅预约订座小程序系统设计与实现
    办公小技巧:word打印怎么做?
    数据结构-树的概念结构及存储
    BetterZip for Mac2024最新mac解压缩软件
    什么是b3dm?b3dm详解
    新时代中国企业数字化转型之BI平台建设
    微服务系列文章之 Nginx反向代理
  • 原文地址:https://blog.csdn.net/qq_44763720/article/details/126949380