友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
52. ThreadLocal
原以为神秘兮兮的 ThreadLocal
是何方神圣?没想到,点开代码,竟然如此简单明了,直接上代码:
1
2
3
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
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
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
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;
}
}
// ……
}
简单解释一下:
当前线程调用 ThreadLocal
类的 set
或 get
方法时,其实是调用的当前线程的 ThreadLocal.ThreadLocalMap threadLocals
变量的 set(ThreadLocal<?> key, Object value)
和 Entry getEntry(ThreadLocal<?> key)
。还有一点需要稍加注意:虽然 ThreadLocal.ThreadLocalMap
名称是以 Map
结尾,但是它并没有实现 Map
接口,只是操作上有些类似。

有一点需要特别注意:ThreadLocalMap
中使用的 key
为 ThreadLocal
的弱引用,而 value
是强引用。所以,如果 ThreadLocal
没有被外部强引用的情况下,在垃圾回收的时候,key
会被清理掉,而 value
不会被清理掉。这样一来,ThreadLocalMap
中就会出现 key
为 null
的 Entry
。假如我们不做任何措施的话,value
永远无法被 GC 回收,这个时候就可能会产生内存泄露。ThreadLocalMap
实现中已经考虑了这种情况,在调用 set()
、get()
、remove()
方法的时候,会清理掉 key
为 null
的记录。使用完 ThreadLocal
方法后 最好手动调用 remove()
方法。
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
package com.diguage.truman.concurrent;
import org.junit.jupiter.api.Test;
/**
* @author D瓜哥, https://www.diguage.com/
* @since 2020-03-09 20:20
*/
public class ThreadLocalTest {
@Test
public void test() {
new Thread(new FirstApp()).start();
}
@Test
public void testInheritableThreadLocal() {
// TODO: InheritableThreadLocal
}
private static class FirstApp implements Runnable {
private ThreadLocal<String> threadLocal
= ThreadLocal.withInitial(() -> "FirstApp-1");
private ThreadLocal<String> threadLocal2
= ThreadLocal.withInitial(() -> "FirstApp-2");
private SecondApp secondApp = new SecondApp();
private ThridApp thridApp = new ThridApp();
@Override
public void run() {
System.out.println(threadLocal.get());
System.out.println(threadLocal2.get());
new Thread(secondApp).start();
thridApp.run();
}
}
private static class SecondApp implements Runnable {
private ThreadLocal<String> threadLocal
= ThreadLocal.withInitial(() -> "SecondApp");
@Override
public void run() {
System.out.println(threadLocal.get());
}
}
private static class ThridApp implements Runnable {
private ThreadLocal<String> threadLocal
= ThreadLocal.withInitial(() -> getClass().getName());
@Override
public void run() {
threadLocal.set("new-ThridApp-value");
System.out.println(threadLocal.get());
}
}
}
关注一下: java.lang.InheritableThreadLocal
。
JDK 的 InheritableThreadLocal
类可以完成父线程到子线程的值传递。但对于使用线程池等会池化复用线程的执行组件的情况,线程由线程池创建好,并且线程是池化起来反复使用的;这时父子线程关系的 ThreadLocal
值传递已经没有意义,应用需要的实际上是把任务提交给线程池时的 ThreadLocal
值传递到 任务执行时。为了解决这个问题,阿里巴巴研发了 alibaba/transmittable-thread-local 库。
哈希冲突了怎么解决?