一、什么是ThreadLocal
-
ThreadLocal是Java中的一个线程局部变量工具类,它提供了线程级别的
变量存储
和访问
操作,每个线程都有自己独立的ThreadLocal实例。 -
一个ThreadLocal对应线程一个局部变量,一个线程可以有多个ThreadLocal,对应多个变量
二、ThreadLocal解决什么问题
- 多线程并发场景可以使用ThreadLocal创建线程独有变量,保证线程数据隔离
- 实现线程范围内的数据共享,可不通过方法参数传递。解决深层次调用的参数传递问题
三、ThreadLocal源码分析
ThreadLocal的实现原理涉及到三个关键的类:ThreadLocal、Thread和ThreadLocalMap。
1. Thread 类(只提取了关键代码解析)
每个线程都有一个Thread对象,其中包含一个ThreadLocalMap对象,用于存储该线程的线程局部变量。在Thread类中,通过ThreadLocal.ThreadLocalMap字段实现对线程局部变量的存取
public
class Thread implements Runnable {
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
}
2. ThreadLocal.ThreadLocalMap类(只提取了关键代码解析)
- ThreadLocalMap是ThreadLocal的内部实现类,是一个自定义的哈希表,用于存储线程局部变量的键值对。
- ThreadLocalMap的键是ThreadLocal实例,值是线程局部变量的值。每个ThreadLocal实例都对应一个键值对,即线程局部变量的值。
public class ThreadLocal<T> {
/**
* ThreadLocalMap is a customized hash map suitable only for
* maintaining thread local values. No operations are exported
* outside of the ThreadLocal class. The class is package private to
* allow declaration of fields in class Thread. To help deal with
* very large and long-lived usages, the hash table entries use
* WeakReferences for keys. However, since reference queues are not
* used, stale entries are guaranteed to be removed only when
* the table starts running out of space.
*/
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 table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* Set the value associated with key.
*
* @param key the thread local object
* @param value the value to be 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)]