1 基本介绍
ThreadLocal 类用来提供线程内部的局部变量,这种变量在多线程环境下访问(通过 get 和 set 方法访问)时能保证各个线程的变量相对独立于其他线程内的变量,分配在堆内的 TLAB 中
ThreadLocal 实例通常来说都是 private static 类型的,属于一个线程的本地变量,用于关联线程和线程上下文。每个线程都会在 ThreadLocal 中保存一份该线程独有的数据,所以是线程安全的
ThreadLocal 作用:
- 线程并发:应用在多线程并发的场景下
- 传递数据:通过 ThreadLocal 实现在同一线程不同函数或组件中传递公共变量,减少传递复杂度
- 线程隔离:每个线程的变量都是独立的,不会互相影响
对比 synchronized:
|
synchronized |
ThreadLocal | |
|
原理 |
同步机制采用以时间换空间的方式,只提供了一份变量,让不同的线程排队访问 |
ThreadLocal 采用以空间换时间的方式,为每个线程都提供了一份变量的副本,从而实现同时访问而相不干扰 |
|
侧重点 |
多个线程之间访问资源的同步 |
多线程中让每个线程之间的数据相互隔离 |
常用方法
|
方法 |
描述 |
|
ThreadLocal<>() |
创建 ThreadLocal 对象 |
|
protected T initialValue() |
返回当前线程局部变量的初始值 |
|
public void set( T value) |
设置当前线程绑定的局部变量 |
|
public T get() |
获取当前线程绑定的局部变量 |
|
public void remove() |
移除当前线程绑定的局部变量 |
2 应用场景
ThreadLocal 适用于下面两种场景:
- 每个线程需要有自己单独的实例
- 实例需要在多个方法中共享,但不希望被多线程共享
ThreadLocal 方案有两个突出的优势:
- 传递数据:保存每个线程绑定的数据,在需要的地方可以直接获取,避免参数直接传递带来的代码耦合问题
- 线程隔离:各线程之间的数据相互隔离却又具备并发性,避免同步方式带来的性能损失
ThreadLocal 用于数据连接的事务管理:
public class JdbcUtils {
// ThreadLocal对象,将connection绑定在当前线程中
private static final ThreadLocal<Connection> tl = new ThreadLocal();
// c3p0 数据库连接池对象属性
private static final ComboPooledDataSource ds = new ComboPooledDataSource();
// 获取连接
public static Connection getConnection() throws SQLException {
//取出当前线程绑定的connection对象
Connection conn = tl.get();
if (conn == null) {
//如果没有,则从连接池中取出
conn = ds.getConnection();
//再将connection对象绑定到当前线程中,非常重要的操作
tl.set(conn);
}
return conn;
}
// ...
}
3 源码解析
在上述代码中,建立的ThreadLocal对象可以通过get方法获取到当前线程独有的信息--在这里是连接对象;如果get不到,那么就会通过ComboPooledDataSource实例化对象通过getConnection方法进行获取,最后将获取的值通过ThreadLocal对象设置当前线程的信息。上述的方法会为每个线程绑定独有的信息,其数据结构如下所示:

每个 Thread 维护一个 ThreadLocalMap,这个 Map 的 key 是 ThreadLocal 实例本身,value 是真正要存储的值
- 每个 Thread 线程内部都有一个 Map (ThreadLocalMap)
- Map 里面存储 ThreadLocal 对象(key)和线程的私有变量(value)
- Thread 内部的 Map 是由 ThreadLocal 维护的,由 ThreadLocal 负责向 map 获取和设置线程的变量值
- 对于不同的线程,每次获取副本值时,别的线程并不能获取到当前线程的副本值,形成副本的隔离,互不干扰
其实在这里我有些疑惑,ThreadLocal对象用来设置线程的独有的信息,通过Map结构实现的,其key是ThreadLocal对象,键、值通过ThreadLocal的set方法设置的,而这个Map是Thread内部的变量,那实际上是如何实现的呢?
get方法
public T get() {
Thread t = Thread.currentThread();//获取当前线程
ThreadLocalMap map = getMap(t);//获取map集合
if (map != null) {//如果map不为null,则获取map中的Entry集合
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {//如果集合不为null,则获取其中的值
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
如上所示,这个获取过程会对ThreadLocalMap对象进行操作,它是ThreadLocal中的内部类,如果有当前线程的ThreadLocalMap不为null的话就会获取当前ThreadLocal对应的值,这样就会为线程独有的信息了。如果不好理解,可以将ThreadLocal对象当作线程中的普通变量;

如果没有当前线程的ThreadLocalMap的话,会进行初始化,再打开setInitialValue方法查看初始化步骤:
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);
}
if (this instanceof TerminatingThreadLocal) {
TerminatingThreadLocal.register((TerminatingThreadLocal<?>) this);
}
return value;
}
如上所示他会再次检查获取当前线程所对应的ThreadLocalMap,会有下面两种情况:
1 map不为null就将当前ThreadLocal对象和值通过set方法设置到ThreadLocalMap中,this指代当前的类对象,而上面的初始化方法是ThreadLocal类中的方法-ThreadLocal实例对象。
2 map为null 为当前线程创建ThreadLocalMap,查看createMap(t,value)方法:
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
线程中的属性threadLocals为它的ThreadLocalMap;我们再查看一下获取线程的ThreadLocalMap的方法:
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
如上,线程中的ThreadLocals就这样被设置了。
上面步骤会新建一个ThreadLocalMap对象,ThreadLocalMap也是ThreadLocal类中的内部类
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;
}
}
/**
* 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);
}
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
其中构造方法如下所示:
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);//通过位运算映射到数组中
table[i] = new Entry(firstKey, firstValue);//新建Entry对象
size = 1;
setThreshold(INITIAL_CAPACITY);//设置扩容阈值
}
他会新建Entry数组,并且计算当前线程所在数组位置,将值包装成Entry对象,并将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;
}
}
如上所示它继承了WeakReference,WeakReference<ThreadLocal<?>>,用于存储 ThreadLocal 变量与其对应的值。其功能如下:
Entry 以 ThreadLocal 作为键(使用弱引用),Object 作为值;通过父类的方法将ThreadLocal对象作为弱应用;
public class WeakReference<T> extends Reference<T> {
/**
* Creates a new weak reference that refers to the given object. The new
* reference is not registered with any queue.
*
* @param referent object the new weak reference will refer to
*/
public WeakReference(T referent) {
super(referent);
}
/**
* Creates a new weak reference that refers to the given object and is
* registered with the given queue.
*
* @param referent object the new weak reference will refer to
* @param q the queue with which the reference is to be registered,
* or <tt>null</tt> if registration is not required
*/
public WeakReference(T referent, ReferenceQueue<? super T> q) {
super(referent, q);
}
}
Reference 是 Java 中用于实现引用对象的抽象基类,位于 java.lang.ref 包中。它为 Java 提供了多种引用类型的支持,如:SoftReference(软引用)、WeakReference(弱引用)、PhantomReference(虚引用)
这些引用类型可以与 垃圾回收器(GC) 协作,用于实现更灵活的对象生命周期管理和内存敏感的资源管理。

上面是get的方法流程,其中包含set方法,查看一下set方法:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
createMap(t, value);
}
}
如上,逻辑和之前很类似,直接查看map.set
private void set(ThreadLocal<?> key, Object value) {
// We don't use a fast path as with get() because it is at
// least as common to use set() to create new entries as
// it is to replace existing ones, in which case, a fast
// path would fail more often than not.
Entry[] tab = table;
int len = tab.length;
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;
}
if (k == null) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
如上,其中for循环的条件,大致意思如下:
1 获取当前索引所在的Entry对象
2 如果其对应索引所在位置为不为null的话,判断对应的键与ThreadLocal对象是否一致;如果一致则更新旧值,如果键为null,说明键已经被回收,就使用新的Entry替换掉旧的。如果都不满足,则使用线性探测法,查看下一个位置;
3 如果其对应索引所在位置为为null的话,那么就直接将Entry对象存入
以上就是ThreadLocal的部分源码分析。
320




被折叠的 条评论
为什么被折叠?



