ThreadLocal,通常叫做线程本地变量或线程本地存储,是用于维持线程封闭性的一种规范方法,它为每个使用某变量的线程都存有一份独立的副本。目的是在多线程环境下保证成员变量的安全,适用于无状态,副本变量独立后不影响业务逻辑的高并发场景。
以数据库连接为例,在单线程应用中可能会维持一个全局的数据库连接,并在程序启动时初始化这个连接对象,从而避免在调用每个方法时都要传递一个Connection对象。但是由于连接对象在多线程应用中并不是线程安全的(比如,线程各自会有关闭连接的操作等),因此将数据库连接保存到ThreadLocal对象中,让每个线程都拥有自己的连接。
private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
ThreadLocal原理
public class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
}
如图所示
- 每个Thread线程内部都有一个ThreadLocalMap,ThreadLocal负责向map获取和设置线程的变量值。
- ThreadLocalMap是ThreadLocal的一个静态内部类,里面存储线程本地对象ThreadLocal的实例(key)和线程的变量副本(value)。
ThreadLocal类的核心方法
protected T initialValue(){}
public T get(){}
public void set(T value){}
public void remove(){}
1.initialValue()
protected T initialValue() {
return null;
}
initialValue() 方法为当前线程初始副本变量值。它是一个protected方法,通常会在使用时进行重写,是一个延迟加载的方法。
2.get()
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null)
return (T)e.value;
}
return setInitialValue();
}
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;
}
get()方法用于获取当前线程的副本变量值。如果没有当前线程的变量值,会调用setInitialValue方法返回value(初始值)。
(1)获取当前线程的ThreadLocalMap对象threadLocals。
(2)如果map不为null且当前线程副本变量的entry节点不为null,从中entry获得value返回。
(3)否则获取初始值null(重写了initialValue() 的话则不为null),如果map不为null,为map设置当前线程副本变量值,并返回value,如果map为null,创建ThreadLocalMap并将ThreadLocal和value初始化到map,然后返回value。
3.set(T value)
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
set()方法用于保存当前线程的副本变量值。
(1)获取当前线程的ThreadLocalMap对象threadLocals。
(2)如果map不为null,则重新将为map设置当前线程副本变量值。
(3)如果map为null,创建ThreadLocalMap并将ThreadLocal和value初始化到map。
4.remove()
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
remove()方法移除当前线程副本变量值。
ThreadLocalMap实现
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal k, Object v){
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
}
在ThreadLocalMap中用Entry来保存数据,其中Key只能为ThreadLocal的实例。Entry是弱引用WeakReference,只能存活到下次GC前。
Hash冲突问题
ThreadLocalMap底层设计比HashMap简单,没有next引用,因此它解决Hash冲突的方式并非链表而是采用线性探测。线性探测根据初始Key的hashcode值确定元素在数组中的位置,如果发现这个位置上已经被占用,则利用固定的算法寻找一定步长的下个位置,依次判断,直至找到能够存放的位置。ThreadLocalMap通过nextIndex(int i, int len)和prevIndex(int i, int len)方法对步长加减1,寻找下一个相邻的位置。
当有大量不同ThreadLocal实例时采用线性探测法解决Hash冲突效率十分低。因此为了避免Hash冲突每个线程尽量只存一个变量,就不会发生hash冲突。如果一个线程要保存多个变量,就要创建多个ThreadLocal,当多个ThreadLocal放入map中时会极大的增加Hash冲突的可能。
弱引用问题
对于Java引用不太理解的可移步至【Java 7之基础 - 强引用、弱引用、软引用、虚引用】。
ThreadLocalMap中Entry的key是弱引用,而Value是强引用。
首先为什么会使用弱引用?
假设在一个方法中新建一个ThreadLocal对象,这时会有一个强引用指向它,在调用set()方法后,线程的ThreadLocalMap对象里的Entry对象又有一个引用 key 指向它。当方法执行完后,栈帧中的强引用被销毁,如果key是强引用,那么对象就不能回收,造成严重的内存泄露。
其次,key是弱引用,value是强引用会导致什么问题?
ThreadLocal在没有外部对象强引用时,弱引用key会在GC时被回收。而value不会回收,因为会有一条当前线程的强引用链。如果创建ThreadLocal的线程一直持续运行(如使用线程池时,线程结束不会被销毁),那么这个Entry对象中的value就有可能一直得不到回收,发生内存泄露。
因此为了避免内存泄漏,需要在调用ThreadLocal的get()、set()方法完成后再调用remove方法,将Entry节点和Map的引用关系移除,这样整个Entry对象就会变成不可达,就可以在GC时被回收。
ThreadLocal简单使用
public class ThreadLocalTest {
ThreadLocal<Long> longLocal = new ThreadLocal<Long>();
ThreadLocal<String> stringLocal = new ThreadLocal<String>();
public void set() {
longLocal.set(Thread.currentThread().getId());
stringLocal.set(Thread.currentThread().getName());
}
public Long getLong() {
return longLocal.get();
}
public String getString() {
return stringLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalTest test = new ThreadLocalTest();
test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
Thread t1 = new Thread() {
public void run() {
//test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
};
};
t1.start();
t1.join();
System.out.println(test.getLong());
System.out.println(test.getString());
}
}
执行结果:
1
main
null
null
1
main
在t1线程中,没有先set,直接get的话会获得其默认值null。因此我们可以在定义ThreadLocal对象时重写initialValue()方法为当前线程初始副本变量值。
public class ThreadLocalTest {
ThreadLocal<Long> longLocal = new ThreadLocal<Long>() {
@Override
protected Long initialValue() {
return Thread.currentThread().getId();
}
};
ThreadLocal<String> stringLocal = new ThreadLocal<String>(){
@Override
protected String initialValue() {
return Thread.currentThread().getName();
}
};
public void set() {
longLocal.set(Thread.currentThread().getId());
stringLocal.set(Thread.currentThread().getName());
}
public Long getLong() {
return longLocal.get();
}
public String getString() {
return stringLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalTest test = new ThreadLocalTest();
//test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
Thread t1 = new Thread() {
public void run() {
//test.set();
System.out.println(test.getLong());
System.out.println(test.getString());
};
};
t1.start();
t1.join();
System.out.println(test.getLong());
System.out.println(test.getString());
}
}
执行结果:
1
main
8
Thread-0
1
main
在main和t1线程中均没有先set()再get(),但由于重写了initialValue()方法,可以获得设置的初始值。