ThreadLocal类并不是用来解决多线程环境下的共享变量问题,而是用来提供线程局部变量。这些变量与普通的变量不同,因为每个访问一个变量的线程(通过其get或set方法)都有自己的、独立初始化的变量副本。ThreadLocal实例通常是类中的私有静态字段,希望将状态与线程关联(例如,用户ID或事务ID)。每个线程都保持对线程本地变量的副本的隐式引用,只要线程是活的并且ThreadLocal实例是可访问的;在线程离开之后,线程本地实例的所有副本都受到垃圾回收(除非存在对这些副本的其他引用)。
实现原理
ThreadLocal实现方式就是ThreadLocal类内部有一个线程安全的ThreadLocalMap,然后用ThreadLocal本身作为Map的key,实例对象作为Map的value,这样就能达到各个线程的值隔离的效果。
ThreadLocalMap
ThreadLocalMap是用来存储与线程关联的value的哈希表,它具有HashMap的部分特性,比如容量、扩容、删除等,它内部通过Entry类来存储key和value。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** 与此ThreadLocal关联的值. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
Entry继承自WeakReference,可以知道,ThreadLocalMap是使用ThreadLocal的弱引用作为Key的。如果一个ThreadLocal没有外部关联的强引用,那么在虚拟机进行垃圾回收时,这个ThreadLocal会被回收,这样,ThreadLocalMap中就会出现key为null的Entry,这些key对应的value也就再无妨访问,但是value却存在一条从Current Thread过来的强引用链。因此只有当Current Thread销毁时,value才能得到释放。
ThreadLocalMap采用线性探查的方式来处理哈希冲突,所以会有一个while循环去查找对应的key,在查找过程中,若发现key为null,即通过弱引用的key被回收,会调用expungeStaleEntry(int)方法,若key为null,则该方法会清理与key对应的value以及Entry。
类名
public class ThreadLocal<T>
变量
/**
* ThreadLocals依赖于附加到每个线程哈希映射(thread.ThreadLocals和inheritablethrreadlocals)。
* ThreadLocal对象充当键,通过threadLocalHashCode进行搜索。
* 这是一个自定义散列代码(仅在ThreadLocalMaps中有用),
* 它消除了在相同线程使用连续构造的threadlocal的常见情况下的冲突,
* 同时在不太常见的情况下保持良好的性能。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* 下一个hash code。原子操作更新。从零开始.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* 连续生成的散列码之间的增量
*/
private static final int HASH_INCREMENT = 0x61c88647;
set(T value)
public void set(T value) {
//返回当前正在执行的线程对象的引用
Thread t = Thread.currentThread();
//获取线程对应的ThreadLocalMap对象
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
当map为null时,调用createMap创建一个map。
createMap(Thread t, T firstValue)
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
可以看出createMap是初始化当前线程的threadLocals变量。所以并不是ThreadLocal中存储线程,而是线程中存储ThreadLocal。
get()
public T get() {
//返回当前正在执行的线程对象的引用
Thread t = Thread.currentThread();
//获取线程对应的ThreadLocalMap对象
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();
}
简单应用
很多时候我们会用SimpleDateFormat来格式化时间,而SimpleDateFormat其实是线程不安全的,我们可以用ThreadLocal封装一个时间工具类。
public class DateUtil {
private static final ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<>();
public static Date getNow() {
return Calendar.getInstance().getTime();
}
public static Date parse(String date, String pattern){
SimpleDateFormat simpleDateFormat = threadLocal.get();
if (simpleDateFormat == null){
simpleDateFormat = new SimpleDateFormat(pattern);
threadLocal.set(simpleDateFormat);
}
try {
return simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String format(Date date, String pattern){
SimpleDateFormat simpleDateFormat = threadLocal.get();
if (simpleDateFormat == null) {
simpleDateFormat = new SimpleDateFormat(pattern);
threadLocal.set(simpleDateFormat);
}
return simpleDateFormat.format(date);
}
}
源码(1.8)
public class ThreadLocal<T> {
/**
* ThreadLocals依赖于附加到每个线程哈希映射(thread.ThreadLocals和inheritablethrreadlocals)。
* ThreadLocal对象充当键,通过threadLocalHashCode进行搜索。
* 这是一个自定义散列代码(仅在ThreadLocalMaps中有用),
* 它消除了在相同线程使用连续构造的threadlocal的常见情况下的冲突,
* 同时在不太常见的情况下保持良好的性能。
*/
private final int threadLocalHashCode = nextHashCode();
/**
* 下一个hash code。原子操作更新。从零开始.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();
/**
* 连续生成的散列码之间的增量
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* 返回下一个hash值
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
/**
* 返回此线程局部变量的当前线程“初始值”。
*
* 此实现只返回null;如果希望线程局部变量具有null以外的值,
* 则必须进行子类化,并重写此方法。通常,将使用匿名内部类
*/
protected T initialValue() {
return null;
}
/**
* 创建线程局部变量。变量的初始值是通过调用Supplier上的get方法来确定的。
* @param supplier 用于确定初始值的供应商
*/
public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
return new SuppliedThreadLocal<>(supplier);
}
public ThreadLocal() {
}
/**
*返回此线程局部变量的当前线程副本中的值。
*如果变量没有当前线程的值,则首先将其初始化为调用initialValue方法返回的值
*/
public T get() {
//返回当前正在执行的线程对象的引用
Thread t = Thread.currentThread();
//获取线程对应的ThreadLocalMap对象
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();
}
/**
* 用于建立初始值的set()的变量
*/
private T setInitialValue() {
T value = initialValue();
//返回当前正在执行的线程对象的引用
Thread t = Thread.currentThread();
//获取线程对应的ThreadLocalMap对象
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
/**
* 将此线程局部变量的当前线程副本设置为指定值。
* 大多数子类无需重写此方法,
* 只需依赖initialValue方法来设置线程局部变量的值。
*
* @param value 要存储在此线程本地副本中的值
*/
public void set(T value) {
//返回当前正在执行的线程对象的引用
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
//获取线程对应的ThreadLocalMap对象
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
/**
* 删除此线程局部变量的当前线程值
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
/**
* 获取与ThreadLocal关联的映射。在InheritableThreadLocal中重写。
* @param t 当前线程
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* 创建与ThreadLocal关联的映射。在InheritableThreadLocal中重写
* @param t 当前线程
* @param firstValue 映射的初始项的值
*/
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
/**
* 创建继承的线程局部变量映射的工厂方法。设计为仅从线程构造函数调用。
* @param parentMap 与父线程关联的映射
* @return 包含父级可继承绑定的映射
*/
static ThreadLocalMap createInheritedMap(ThreadLocalMap parentMap) {
return new ThreadLocalMap(parentMap);
}
/**
* childValue方法在子类InheritableThreadLocal中定义,
* 但在这里是内部定义的,目的是提供CreateInheritabledMap工厂方法,
* 而无需在InheritableThreadLocal中对map类进行子类划分。
*/
T childValue(T parentValue) {
throw new UnsupportedOperationException();
}
/**
* 从指定的Supplier获取初始值的ThreadLocal的扩展。
*/
static final class SuppliedThreadLocal<T> extends ThreadLocal<T> {
private final Supplier<? extends T> supplier;
SuppliedThreadLocal(Supplier<? extends T> supplier) {
this.supplier = Objects.requireNonNull(supplier);
}
@Override
protected T initialValue() {
return supplier.get();
}
}
/**
*ThreadLocalMap是一个定制的散列映射,仅适用于维护线程本地值。
*在ThreadLocal类之外不作任何操作。该类是包私有的,允许在类线程中声明字段。
*为了帮助处理非常大且使用寿命长的用法,哈希表条目使用WeakReferences作为键。
*但是,由于不使用引用队列,因此只有当表开始耗尽空间时,才保证删除过时的条目
*/
static class ThreadLocalMap {
/**
*此哈希映射中的条目使用其主ref字段作为键(始终是ThreadLocal对象)
* 扩展WeakReference。请注意,
*空键(即entry.get()==null)意味着不再引用该键,
*因此可以从表中删除该项。这些条目在下面的代码中称为“过时条目”。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** 与此ThreadLocal关联的值。 */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 初始容量必须是2的幂次方。
*/
private static final int INITIAL_CAPACITY = 16;
/**
* 根据需要调整大小。表的长度必须是2的幂次方。
*/
private Entry[] table;
/**
* table的大小
*/
private int size = 0;
/**
* 下一个要调整大小的大小值。
*/
private int threshold; // Default to 0
/**
* 将“调整大小阈值”设置为在最坏情况下保持2/3的负载系数。
*/
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);
}
/**
* 构造一个最初包含(firstKey,firstValue)的新映射。
* ThreadLocalMaps是按需地构建的,
* 只有当我们至少有一个条目要放进去时,才会创建一个。
*/
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);
}
/**
* 构造一个新映射,其中包含来自给定父映射的所有可继承线程局部变量。
* 仅由CreateInheriteMap调用。
*
* @param parentMap 与父线程关联的映射。
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
/**
* 获取项。此方法本身只处理快速路径:
* 现有key的直接命中。否则它将转发到getEntryAfterMiss。
* 这是为了最大限度地提高性能直接命中
*/
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
return getEntryAfterMiss(key, i, e);
}
/**
* 在其直接哈希槽中找不到key时使用的getEntry方法的版本。
* @param key the thread local object
* @param i the table index for key's hash code
* @param e the entry at table[i]
* @return the entry associated with key, or null if no such
*/
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;
}
/**
* 设置值。
* @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)]) {
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();
}
/**
* Remove the entry for key.
*/
private void remove(ThreadLocal<?> key) {
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)]) {
if (e.get() == key) {
e.clear();
expungeStaleEntry(i);
return;
}
}
}
/**
* 用指定键的项替换set操作期间遇到的过时项。
* @param key the key
* @param value the value to be associated with key
* @param staleSlot index of the first stale entry encountered while
* searching for key.
*/
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
// 备份以检查当前运行中以前的陈旧条目。
// 我们一次清理整个运行,以避免由于垃圾收集器释放
// 成束的ref(即每当收集器运行时)而导致持续的增量重新灰化。
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
// Find either the key or trailing null slot of run, whichever
// occurs first
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
// If we find key, then we need to swap it
// with the stale entry to maintain hash table order.
// The newly stale slot, or any other stale slot
// encountered above it, can then be sent to expungeStaleEntry
// to remove or rehash all of the other entries in run.
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
// Start expunge at preceding stale entry if it exists
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
// If we didn't find stale entry on backward scan, the
// first stale entry seen while scanning for key is the
// first still present in the run.
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
// If key not found, put new entry in stale slot
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
/**
* 删除过时的entry
*/
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// 删除staleSlot位置的entry
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// 重新hash直到tab[i]为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;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
/**
* 试探性地扫描一些单元格以查找过时的条目
*/
private boolean cleanSomeSlots(int i, int n) {
boolean removed = false;
Entry[] tab = table;
int len = tab.length;
do {
i = nextIndex(i, len);
Entry e = tab[i];
if (e != null && e.get() == null) {
n = len;
removed = true;
i = expungeStaleEntry(i);
}
} while ( (n >>>= 1) != 0);
return removed;
}
/**
* 重新hash和或调整table的大小
*/
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
/**
* 容量增加一倍
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (int j = 0; j < oldLen; ++j) {
Entry e = oldTab[j];
if (e != null) {
ThreadLocal<?> k = e.get();
if (k == null) {
e.value = null; // Help the GC
} else {
int h = k.threadLocalHashCode & (newLen - 1);
while (newTab[h] != null)
h = nextIndex(h, newLen);
newTab[h] = e;
count++;
}
}
}
setThreshold(newLen);
size = count;
table = newTab;
}
/**
* 删除表中所有null值.
*/
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
}
}
更多精彩内容请关注微信公众号: