一、前言
ThreadLocal是Java中一个非常有用的工具类,它提供了一种线程本地存储的机制,可以让我们在同一线程内共享数据而不用担心线程安全问题。在并发编程中,使用ThreadLocal可以避免多线程间对同一变量的竞争和冲突,使得代码更加简洁和安全。本篇文章将从源码层面对ThreadLocal的实现原理进行分析。
二、ThreadLocal的实现原理
ThreadLocal提供了一个线程本地存储的机制,可以让我们在同一线程内共享数据而不用担心线程安全问题。下面我们来看看ThreadLocal的实现原理。
- ThreadLocal的基本原理
ThreadLocal的实现原理非常简单,每个Thread内部都维护了一个ThreadLocalMap对象,ThreadLocalMap对象是一个定制化的HashMap,用于存储线程的局部变量。当我们调用ThreadLocal的get()方法时,它会首先获取当前线程,然后从当前线程的ThreadLocalMap对象中获取对应的值;当我们调用ThreadLocal的set()方法时,它会首先获取当前线程,然后将对应的值存储到当前线程的ThreadLocalMap对象中。因此,ThreadLocal提供了一种线程本地存储的机制,可以让我们在同一线程内共享数据而不用担心线程安全问题。
2. ThreadLocalMap的实现原理
ThreadLocalMap是ThreadLocal的核心实现类,它是一个定制化的HashMap,用于存储线程的局部变量。下面我们来看看ThreadLocalMap的实现原理。
2.1 Entry类
ThreadLocalMap中存储的是一个个Entry对象,Entry对象包含了两个属性,一个是ThreadLocal对象,另一个是值对象。ThreadLocal对象用于标识不同的线程局部变量,值对象则表示具体的值。Entry类的代码如下:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
2.2 ThreadLocalMap的基本操作
ThreadLocalMap提供了四个基本操作,分别是get、set、remove和replaceStaleEntry。下面我们逐一分析这些操作的实现原理。
2.2.1 get操作
get操作的主要作用是从ThreadLocalMap中获取对应的值。具体实现可以参考下面的代码:
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);
}
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();
}
getEntryAfterMiss()方法是一个私有方法,它用于在发生哈希冲突时进行查找。具体实现可以参考下面的代码:
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;
}
2.2.2 set操作
set操作的主要作用是向ThreadLocalMap中存储对应的值。具体实现可以参考下面的代码:
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();
}
2.2.3 remove操作
remove操作的主要作用是从ThreadLocalMap中删除对应的值。具体实现可以参考下面的代码:
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;
}
}
}
2.2.4 replaceStaleEntry操作
replaceStaleEntry操作的主要作用是在插入新的Entry时,清除已经被垃圾回收的Entry对象。具体实现可以参考下面的代码:
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
// Back up to check for prior stale entry in current run.
// We clean out whole runs at a time to avoid continual
// incremental rehashing due to garbage collector freeing
// up refs in bunches (i.e., whenever the collector runs).
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);
}
2.2.5 expungeStaleEntry操作
expungeStaleEntry操作的主要作用是删除已经被垃圾回收的Entry对象。具体实现可以参考下面的代码:
private void expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
// expunge entry at staleSlot
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
// Rehash until we encounter 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;
// Unlike Knuth 6.4 Algorithm R, we must scan until
// null because multiple entries could have been stale.
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
}
三、总结
ThreadLocal是Java中的一个重要的线程局部变量,可以用于在一个线程中共享变量。ThreadLocal底层使用了ThreadLocalMap来实现变量的存储和访问,每个线程都有自己的ThreadLocalMap,使用哈希表来存储变量。ThreadLocalMap使用Entry来表示每个键值对,Entry继承了弱引用,避免了内存泄漏问题。在进行get操作时,ThreadLocalMap会根据ThreadLocal对象的哈希值查找对应的Entry对象,然后返回值;在进行set操作时,ThreadLocalMap会根据ThreadLocal对象的哈希值查找对应的Entry对象,如果找到了就将值更新,否则就创建新的Entry对象;在进行remove操作时,ThreadLocalMap会根据ThreadLocal对象的哈希值查找对应的Entry对象,然后删除。