对ThreadLocal的理解
ThreadLocal线程本地变量,ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量。 如下一个线程不安全的例子:
public class ConnectionManager {
private static Connection connection = null;
public static Connection openConnection(){
if (connection == null){
try {
connection = DriverManager.getConnection("");
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
public static void closeConnection(){
if (connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这段数据库链接管理的类,在单线程中是没有问题,但是在多线程中使用就会存在线程安全的问题.第一, 这里面的2个方法都没有进行同步,很可能在openConnection方法中会多次创建connect;第二,由于connect是共享变量,那么必然在调用connect的地方需要使用到同步来保障线程安全,因为很可能一个线程在使用connect进行数据库操作,而另外一个线程调用closeConnection关闭链接。
所以处于线程安全的考虑,必须将这段代码的两个方法进行同步处理,并且在调用connect的地方需要进行同步处理。
这样将会大大影响程序执行效率,因为一个线程在使用connect进行数据库操作的时候,其他线程只有等待。
假如每个线程中都有一个connect变量,各个线程之间对connect变量的访问实际上是没有依赖关系的,即一个线程不需要关心其他线程是否对这个connect进行了修改的。
既然不需要在线程之间共享这个变量,可以直接这样处理,在每个需要使用数据库连接的方法中具体使用时才创建数据库链接(为什么局部变量是线程安全的),然后在方法调用完毕再释放这个连接,如:
class ConnectionManager {
private Connection connect = null;
public Connection openConnection() {
if(connect == null){
connect = DriverManager.getConnection();
}
return connect;
}
public void closeConnection() {
if(connect!=null)
connect.close();
}
}
class Dao{
public void insert() {
ConnectionManager connectionManager = new ConnectionManager();
Connection connection = connectionManager.openConnection();
//使用connection进行操作
connectionManager.closeConnection();
}
}
这样处理确实也没有任何问题,由于每次都是在方法内部创建的连接,那么线程之间自然不存在线程安全问题。但是这样会有一个致命的影响:导致服务器压力非常大,并且严重影响程序执行性能。由于在方法中需要频繁地开启和关闭数据库连接,这样不尽严重影响程序执行效率,还可能导致服务器压力巨大。
ThreadLocal在每个线程中对该变量会创建一个副本,即每个线程内部都会有一个该变量,且在线程内部任何地方都可以使用,线程之间互不影响,这样一来就不存在线程安全问题,也不会严重影响程序执行性能。
虽然ThreadLocal能够解决上面说的问题,但是由于在每个线程中都创建了副本,所以要考虑它对资源的消耗,比如内存的占用会比不使用ThreadLocal要大。
深入解析ThreadLocal类
先了解一下ThreadLocal类提供的几个内部方法
public T get() { }
public void set(T value) { }
public void remove() { }
protected T initialValue() { }
get()方法是用来获取ThreadLocal在当前线程中保存的变量副本,set()用来设置当前线程中变量的副本,remove()用来移除当前线程中变量的副本,initialValue()是一个protected方法,一般是用来在使用时进行重写的,它是一个延迟加载方法,
首先我们看ThreadLocal是如何为每个线程创建一个变量的副本.
先看get方法的实现:
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();
}
protected T initialValue() {
return null;
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal.ThreadLocalMap threadLocals = null;
第一句是取得当前线程,然后通过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap。然后接着下面获取到<key,value>键值对,注意这里获取键值对传进去的是 this,而不是当前线程t。如果获取成功,则返回value值。 如果map为空,则调用setInitialValue方法返回value.我们上面的每一句来仔细分析:首先看一下getMap方法中做了什么: 在getMap中,是调用当期线程t,返回当前线程t中的一个成员变量threadLocals,Thread的成员变量threadLocals实际上就是一个ThreadLocalMap,这个类型是ThreadLocal类的一个内部类
ThreadLocalMap的内部实现:
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;
}
}
}
ThreadLocalMap的Entry继承了WeakReference,并且使用ThreadLocal作为键值
这里使用到里弱引用,简单说明下: 弱引用也是用来描述非必需对象的,当JVM进行垃圾回收时,无论内存是否充足,该对象仅仅被弱引用关联,那么就会被回收。Java中几种引用的理解
当仅仅只有ThreadLocalMap中的Entry的key指向ThreadLocal的时候,ThreadLocal会进行回收的!!!
ThreadLocal被垃圾回收后,在ThreadLocalMap里对应的Entry的键值会变成null,但是Entry是强引用,那么Entry里面存储的Object,并没有办法进行回收,所以ThreadLocalMap 做了一些额外的回收工作。

setInitialValue方法的具体实现:如果map不为空,就设置键值对,为空,再创建Map
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;
}
看一下createMap的实现
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
至此我们已经明白了ThreadLocal是如何为每个线程创建变量的副本的:首先,在每个线程Thread内部有一个ThreadLocal.ThreadLocalMap类型的成员变量threadLocals,这个threadLocals就是用来存储实际的变量副本的,键值为当前ThreadLocal变量,value为变量副本(即T类型的变量)。
初始时,在Thread里面,threadLocals为空,当通过ThreadLocal变量调用get()方法或者set()方法,就会对Thread类中的threadLocals进行初始化,并且以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为value,存到threadLocals。
Thread、ThreadLocalMap、ThreadLocal总览图:

Thread类有属性变量threadLocals (类型是ThreadLocal.ThreadLocalMap),也就是说每个线程有一个自己的ThreadLocalMap ,所以每个线程往这个ThreadLocal中读写隔离的,并且是互相不会影响的。
一个ThreadLocal只能存储一个Object对象,如果需要存储多个Object对象那么就需要多个ThreadLocal!!! 如图:

然后在当前线程里面,如果要使用副本变量,就可以通过get方法在threadLocals里面查找。
下面通过一个例子来证明通过ThreadLocal能达到在每个线程中创建变量副本的效果:
public class ThreadLocalTest {
ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();
ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
public void set(){
longThreadLocal.set(Thread.currentThread().getId());
stringThreadLocal.set(Thread.currentThread().getName());
}
public long getLong(){
return longThreadLocal.get();
}
public String getString(){
return stringThreadLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalTest threadLocalTest = new ThreadLocalTest();
threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
Thread thread = new Thread(){
@Override
public void run() {
threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
};
thread.start();
thread.join();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
}
结果为:
1
main
11
Thread-0
1
main
从这段代码的输出结果可以看出,在main线程中和thread0线程中,longLocal保存的副本值和stringLocal保存的副本值都不一样。最后一次在main线程再次打印副本值是为了证明在main线程中和thread1线程中的副本值确实是不同的。
总结一下:
- 实际的通过ThreadLocal创建的副本是存储在每个线程自己的threadLocals中的;
- 为何threadLocals的类型ThreadLocalMap的键值为ThreadLocal对象,因为每个线程中可有多个threadLocal变量,就像上面代码中的longLocal和stringLocal;
- 在进行get之前,必须先set,否则会报空指针异常;
如果想在get之前不需要调用set就能正常访问的话,必须重写initialValue()方法。
因为在上面的代码分析过程中,我们发现如果没有先set的话,即在map中查找不到对应的存储,则会通过调用setInitialValue方法返回i,而在setInitialValue方法中,有一个语句是T value = initialValue(), 而默认情况下,initialValue方法返回的是null。
public class ThreadLocalTest {
ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();
ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
public void set(){
longThreadLocal.set(Thread.currentThread().getId());
stringThreadLocal.set(Thread.currentThread().getName());
}
public long getLong(){
return longThreadLocal.get();
}
public String getString(){
return stringThreadLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalTest threadLocalTest = new ThreadLocalTest();
threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
Thread thread = new Thread(){
@Override
public void run() {
threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
};
thread.start();
thread.join();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
}
在main线程中,没有先set,直接get的话,运行时会报空指针异常。
如下方法重写了initialValue() 方法,可以先不set而直接get就可以了
public class ThreadLocalTest {
// ThreadLocal<Long> longThreadLocal = new ThreadLocal<>();
// ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();
ThreadLocal<Long> longThreadLocal = new ThreadLocal<Long>(){
@Override
protected Long initialValue() {
return Thread.currentThread().getId();
};
};
ThreadLocal<String> stringThreadLocal = new ThreadLocal<String>(){;
@Override
protected String initialValue() {
return Thread.currentThread().getName();
};
};
// public void set(){
// longThreadLocal.set(Thread.currentThread().getId());
// stringThreadLocal.set(Thread.currentThread().getName());
// }
public long getLong(){
return longThreadLocal.get();
}
public String getString(){
return stringThreadLocal.get();
}
public static void main(String[] args) throws InterruptedException {
final ThreadLocalTest threadLocalTest = new ThreadLocalTest();
// threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
Thread thread = new Thread(){
@Override
public void run() {
// threadLocalTest.set();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
};
thread.start();
thread.join();
System.out.println(threadLocalTest.getLong());
System.out.println(threadLocalTest.getString());
}
}
ThreadLocal使用式例代码:
public class ThreadLocalTest2 {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
threadLocal.set(i);
System.out.println(Thread.currentThread().getName()+"===="+threadLocal.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
threadLocal.remove();
}
}
},"threadLocal1").start();
new Thread(()->{
for (int i = 0; i < 100; i++) {
threadLocal.set(i);
System.out.println(Thread.currentThread().getName()+"====="+threadLocal.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
threadLocal.remove();
}
}
},"threadLocal2").start();
}
}
运行结果:
threadLocal1====0
threadLocal2=====0
threadLocal2=====1
threadLocal1====1
threadLocal1====2
threadLocal2=====2
threadLocal2=====3
threadLocal1====3
threadLocal1====4
threadLocal2=====4
threadLocal1====5
threadLocal2=====5
threadLocal1====6
threadLocal2=====6
threadLocal1====7
threadLocal2=====7
threadLocal1====8
threadLocal2=====8
threadLocal1====9
threadLocal2=====9
threadLocal1====10
threadLocal2=====10
从运行的结果我们可以看到threadLocal1进行set值对threadLocal2并没有任何影响!
ThreadLocal应用场景
ThreadLocal归纳下来就2类用途:
- 保存线程上下文信息,在任意需要的地方可以获取
- 线程安全的,避免某些情况需要考虑线程安全必须同步带来的性能损失
最常见的应用场景为解决数据库连接、Session管理等. 如:
private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
return DriverManager.getConnection(DB_URL);
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
private static final ThreadLocal threadSession = new ThreadLocal();
public static Session getSession() throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
s = getSessionFactory().openSession();
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}
ThreadLocal为解决多线程程序的并发问题提供了一种新的思路,但是ThreadLocal也有局限性,我们来参考阿里规范:

每个线程往ThreadLocal中读写数据是线程隔离,互相之间不会影响的,所以ThreadLocal无法解决共享对象的更新问题!
由于不需要共享信息,自然就不存在竞争问题了,从而保证了某些情况下线程的安全,以及避免了某些情况需要考虑线程安全必须同步带来的性能损失!!!
阿里巴巴规范里SimpleDateFormat里的实现:
