To put it simply, a ThreadLocal is shared in a thread and isolated between different threads. (Each thread can only see the value of its own thread). As shown below:
Before using Threadlocal, let’s take a look at the following API:
The API of the ThreadLocal class is very simple. The more important ones here are get(), set(), and remove(). set is used for assignment operations, and get is used to obtain variables. Value, remove is to delete the value of the current variable. It should be noted that the initialValue method will be triggered when it is called for the first time and is used to initialize the current variable value. By default, initialValue returns null.
Now that we have finished talking about the API of the ThreadLocal class, let’s practice it to understand the previous sentence: A ThreadLocal is shared in a thread. It is isolated between different threads (each thread can only see the value of its own thread)
public class ThreadLocalTest { private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() { // 重写这个方法,可以修改“线程变量”的初始值,默认是null @Override protected Integer initialValue() { return 0; } }; public static void main(String[] args) throws InterruptedException { //一号线程 new Thread(new Runnable() { @Override public void run() { System.out.println("一号线程set前:" + threadLocal.get()); threadLocal.set(1); System.out.println("一号线程set后:" + threadLocal.get()); } }).start(); //二号线程 new Thread(new Runnable() { @Override public void run() { System.out.println("二号线程set前:" + threadLocal.get()); threadLocal.set(2); System.out.println("二号线程set后:" + threadLocal.get()); } }).start(); //主线程睡1s Thread.sleep(1000); //主线程 System.out.println("主线程的threadlocal值:" + threadLocal.get()); } }
Explain the above code a little:
Each ThreadLocal instance is similar to A variable name, different ThreadLocal instances are different variable names, and there will be a value inside them (understood this way for the time being). The "ThreadLocal variable or thread variable" mentioned in the following description represents an instance of the ThreadLocal class.
Create a static "ThreadLocal variable" in the class, create two threads in the main thread, and set the ThreadLocal variables to 1 and 2 in these two threads respectively. Then wait for threads No. 1 and 2 to finish executing, and check the value of the ThreadLocal variable in the main thread.
Program results and analysis⌛
The key point of the program results is that the output of the main thread is 0. If it is an ordinary variable, the number one thread and Set the ordinary variables to 1 and 2 in the second thread, then print this variable after the first and second threads are executed, and the output value must be 1 or 2 (which one is output depends on the thread scheduling logic of the operating system). However, after using the ThreadLocal variable to assign values through two threads, the initial value 0 is output in the main thread thread. This is why "a ThreadLocal is shared in a thread and isolated between different threads". Each thread can only see the value of its own thread. This is the core role of ThreadLocal: to implement threads Scoped local variables.
Each Thread object has a ThreadLocalMap. When a ThreadLocal is created, the ThreadLocal object will be added to the Map. , where the key is ThreadLocal and the value can be of any type. You may not understand this sentence very well when you first read it, but we will understand it after reading the source code together.
Our previous understanding was that all constant values or reference types are stored in ThreadLocal instances, but in fact they are not. This statement just allows us to better understand the concept of ThreadLocal variables. . Storing a value to ThreadLocal actually stores a value to the ThreadLocalMap in the current thread object. ThreadLocalMap can be simply understood as a Map, and the key to store a value in this Map is the ThreadLocal instance itself.
????In other words, the data in ThreadLocal that you want to store is not actually stored in the ThreadLocal object. Instead, this ThreadLocal instance is used as a key and stored in a Map in the current thread. The same is true when obtaining the value of ThreadLocal. This is why ThreadLocal can achieve isolation between threads.
ThreadLocalMap is an internal class of ThreadLocal, which implements a set of its own Map structure✨
ThreadLocalMap attribute:
static class Entry extends WeakReference<ThreadLocal<?>> { Object value; Entry(ThreadLocal<?> k, Object v) { super(k); value = v; } } //初始容量16 private static final int INITIAL_CAPACITY = 16; //散列表 private Entry[] table; //entry 有效数量 private int size = 0; //负载因子 private int threshold;
ThreadLocalMap sets ThreadLocal Variable
private void set(ThreadLocal<?> key, Object value) { Entry[] tab = table; int len = tab.length; //与运算 & (len-1) 这就是为什么 要求数组len 要求2的n次幂 //因为len减一后最后一个bit是1 与运算计算出来的数值下标 能保证全覆盖 //否者数组有效位会减半 //如果是hashmap 计算完下标后 会增加链表 或红黑树的查找计算量 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; } //槽点被GC掉 重设状态 if (k == null) { replaceStaleEntry(key, value, i); return; } } //槽点为空 设置value tab[i] = new Entry(key, value); //设置ThreadLocal数量 int sz = ++size; //没有可清理的槽点 并且数量大于负载因子 rehash if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); }
ThreadLocalMap attribute introduction????:
is stored in an array similar to ordinary Hashmap, but it is different from the zipper method used by hashmap to solve hash conflicts. ThreadLocalMap uses the open address method
The initial capacity of the array is 16, the load factor is 2/3
The key of the node node encapsulates WeakReference for Recycling
Stored in Thread, there are two ThreadLocalMap variables
threadLocals in ThreadLocal The creation in the object method set is also maintained by ThreadLocal
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
inheritableThreadLocals is similar to ThreadLocal and InheritableThreadLocal overrides the createMap method
void createMap(Thread t, T firstValue) { t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue); }
inheritableThreadLocals 作用是将ThreadLocalMap传递给子线程
init方法中 条件满足后直接为子线程创建ThreadLocalMap
注意:
仅在初始化子线程的时候会传递 中途改变副线程的inheritableThreadLocals 变量 不会将影响结果传递到子线程 。
使用线程池要注意 线程不回收 尽量避免使用父线程的inheritableThreadLocals 导致错误
为什么要用弱引用,官方是这样回答的
To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys.
为了处理非常大和生命周期非常长的线程,哈希表使用弱引用作为 key。
生命周期长的线程可以理解为:线程池的核心线程
ThreadLocal在没有外部对象强引用时如Thread,发生GC时弱引用Key会被回收,而Value是强引用不会回收,如果创建ThreadLocal的线程一直持续运行如线程池中的线程,那么这个Entry对象中的value就有可能一直得不到回收,发生内存泄露。
key 使用强引用????: 引用的ThreadLocal的对象被回收了,但是ThreadLocalMap还持有ThreadLocal的强引用,如果没有手动删除,ThreadLocal不会被回收,导致Entry内存泄漏。
key 使用弱引用????: 引用的ThreadLocal的对象被回收了,由于ThreadLocalMap持有ThreadLocal的弱引用,即使没有手动删除,ThreadLocal也会被回收。value在下一次ThreadLocalMap调用set,get,remove的时候会被清除。
Java8中已经做了一些优化如,在ThreadLocal的get()、set()、remove()方法调用的时候会清除掉线程ThreadLocalMap中所有Entry中Key为null的Value,并将整个Entry设置为null,利于下次内存回收。
强引用????: 如果一个对象具有强引用,它就不会被垃圾回收器回收。即使当前内存空间不足,JVM也不会回收它,而是抛出 OutOfMemoryError 错误,使程序异常终止。如果想中断强引用和某个对象之间的关联,可以显式地将引用赋值为null,这样一来的话,JVM在合适的时间就会回收该对象
软引用????: 在使用软引用时,如果内存的空间足够,软引用就能继续被使用,而不会被垃圾回收器回收,只有在内存不足时,软引用才会被垃圾回收器回收。(软引用可用来实现内存敏感的高速缓存,比如网页缓存、图片缓存等。使用软引用能防止内存泄露,增强程序的健壮性)
弱引用????: 具有弱引用的对象拥有的生命周期更短暂。因为当 JVM 进行垃圾回收,一旦发现弱引用对象,无论当前内存空间是否充足,都会将弱引用回收。不过由于垃圾回收器是一个优先级较低的线程,所以并不一定能迅速发现弱引用对象
虚引用????: 虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。虚引用必须和引用队列(ReferenceQueue)联合使用。当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之关联的引用队列中。(注意哦,其它引用是被JVM回收后才被传入ReferenceQueue中的。由于这个机制,所以虚引用大多被用于引用销毁前的处理工作。可以使用在对象销毁前的一些操作,比如说资源释放等。)
通常ThreadLocalMap的生命周期跟Thread(注意线程池中的Thread)一样长,如果没有手动删除对应key(线程使用结束归还给线程池了,其中的KV不再被使用但又不会GC回收,可认为是内存泄漏),一定会导致内存泄漏,但是使用弱引用可以多一层保障:弱引用ThreadLocal会被GC回收,不会内存泄漏,对应的value在下一次ThreadLocalMap调用set,get,remove的时候会被清除,Java8已经做了上面的代码优化。
The above is the detailed content of How to use ThreadLocal class in Java?. For more information, please follow other related articles on the PHP Chinese website!