一、ThreadLocal简介
ThreadLocal用于将自定义变量和当前线程绑定,每个线程都拥有自己独立的自定义变量。这些变量可以用来保存一些状态信息,例如用户信息、Span信息、或者非线程安全的对象。
举例:
SimpleDateFormat是线程不安全的类多线程使用会有并发问题。那么我们可以利用ThreadLoca来解决这个问题。(或者使用JDK8的Datetimeformatter类)
图1:
public static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() { @Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
} };
这样每个线程就会拥有一个属于自己的SimpleDateFormat对象,每个线程只使用自己的SimpleDateFormat对象那么就不存在并发问题了。
二、源码分析
那么ThreadLocal是怎么做到这么强大的功能的呢?
首先从get()方法入手
public T get() {
Thread t = Thread.currentThread();// 获取当前线程
ThreadLocalMap map = getMap(t);
// 如果map已经被初始化直接取值
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
// 如果没有被初始化过则初始化一个值
return setInitialValue();
}
// 获取Thread的threadLocals变量
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
// 设置初始值并返回
private T setInitialValue() {
T value = initialValue();// 此处调用我们定义好的初始化方法获取对象
Thread t = Thread.currentThread();// 获取当前线程
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
接下来看Thread的threadLocals字段,这是Thread的一个字段,类型是ThreadLocal.ThreadLocalMap这是用来存储我们自定义的变量的。ThreadLocalMap内容如下:
首先这事一个类似Map的数据结构,Entry结构如下:
// 这个Entry是一个弱引用
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
可以发现这个Entry是一个弱引用(弱引用作用:https://blog.csdn.net/han_dada/article/details/77511675)可以看到这个Map是以当前的ThreadLocal对象(图1中的df)为key,自定义的对象为value存储的。也就是我们定义的对象(图1中的SimpleDateFormat对象)会被以以下结构存储。
也就是整个get方法的流程是:获取当前线程,获取当前线程的threadLocals对象,从中取出对应的自定义对象,到这里已经完成了ThreadLocal的应有的功能。
但是为什么这个Entry是弱引用呢?一定是做了什么不可描述的事情。
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
// 出现miss
return getEntryAfterMiss(key, i, e);
}
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;
}
// 清除过期Entry
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter null
Entry e;
int i;
for (i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null;
tab[i] = null;
size--;
} else {
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
重点在清除过期Entry方法,也就是说如果弱引用因为过期导致key被回收了,那么清除一次所有过期的key的Entry。其实在set和remove方法又同样的清除过期Entry逻辑。为的就是保证引用的ThreadLocal
的对象被回收了,由于ThreadLocalMap
持有ThreadLocal
的弱引用,即使没有手动删除,ThreadLocal
也会被回收。value
在下一次ThreadLocalMap
调用set
,get
,remove
的时候会被清除。相当于多一层保障防止内存泄漏。
但是这里还是有可能导致内存泄漏。由于ThreadLocalMap
的生命周期跟Thread
一样长,如果没有手动删除对应key
就会导致内存泄漏,而不是因为弱引用。比如图1的静态字段的引用而且一只没有remove。这里是需要注意的记得释放呦。
三、注意事项
注意有可能导致内存泄漏的情况。
四、扩展
InheritableThreadLocal:
InheritableThreadLocal就如它的名字一样解决的问题就是父线程的变量要传递到子线程。
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
可以看到其实InheritableThreadLocal是ThreadLocal的子类其实没什么太大区别只是操作的字段变成了inheritableThreadLocals的那么它是怎么做到父线程的变量要传递到子线程的呢?看一下Thread的构造方法调用的init方法如下:
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
...
}
创建线程的时候用复制了以下父线程的inheritableThreadLocals对象。原来奥秘就在这里!!!
注意:
1.对于可变对象由于子线程和父线程持有的是相同对象的引用,所以修改任意自定义对象内容都会跟着变化。
public class TestThreadLocal {
private int i = 0;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public String toString() {
return "" + i;
}
public TestThreadLocal(int i) {
this.i = i;
}
public static InheritableThreadLocal<TestThreadLocal> d = new InheritableThreadLocal();
public static void main(String[] args) throws InterruptedException {
d.set(new TestThreadLocal(0));
System.out.println("father-get1-" + d.get());
new Thread(() -> {
System.out.println("child-get1-" + d.get());
try {
// 等待父线程执行
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("child-get2-" + d.get());
}).start();
// 等待子线程执行
Thread.sleep(500);
d.get().setI(100);
System.out.println("father-get2-" + d.get());
}
}
结果:
father-get1-0
child-get1-0
father-get2-100
child-get2-100
2.如果是通过InheritableThreadLocal.set修改对象引用子线程初始化后在修改父线程的inheritableThreadLocals内的对象是不会随动的。
public class TestThreadLocal {
private int i = 0;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
@Override
public String toString() {
return "" + i;
}
public TestThreadLocal(int i) {
this.i = i;
}
public static InheritableThreadLocal<TestThreadLocal> d = new InheritableThreadLocal();
public static void main(String[] args) {
d.set(new TestThreadLocal(0));
System.out.println("father-get1-" + d.get());
new Thread(() -> {
System.out.println("child-get1-" + d.get());
try {
// 等待父线程修改
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("child-get2-" + d.get());
}).start();
d.set(new TestThreadLocal(10000));
System.out.println("father-get2-" + d.get());
}
}
结果:
father-get1-0
child-get1-0
father-get2-10000
child-get2-0