1. 作用
- 传递数据:保存每个线程绑定的数据,在需要的地方可以直接获取,避免参数直接传递带来的代码耦合
- 线程隔离:各线程间的数据相互隔离却又具备并发性,避免同步方法带来的性能损失
2. 代码实现
public class Test {
public static ThreadLocal<Latte> threadLocal = new ThreadLocal();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
Latte latte = new Latte();
latte.setName("拿铁1");
latte.setPrice(BigDecimal.TEN);
threadLocal.set(latte);
getValue();
}, "t1");
t1.start();
Thread t2 = new Thread(() -> {
Latte latte = new Latte();
latte.setName("拿铁2");
latte.setPrice(BigDecimal.ONE);
threadLocal.set(latte);
getValue();
}, "t2");
t2.start();
getValue();
}
public static void getValue() {
Latte latte = threadLocal.get();
String name = Thread.currentThread().getName();
System.out.println("线程名:" + name + "latte = " + latte);
}
}
3. 内存泄漏
1. ThreadLocal造成内存泄露的前提
- 没有手动删除当前线程中ThreadLocalMap里的具体entry
- 当前线程依然在运行
综上:由于ThreadLocalMap是Thread的一个属性,所以ThreadLocal的生命周期和Thread是一样长的,如果没有手动删除不再使用的ThreadLocal,就会导致内存泄露
2. 避免ThreadLocal内存泄露方式
- 使用完ThreadLocal,调用其remove方法删除对应的Entry
- 使用完ThreadLocal,当前Thread也随之运行结束
3. ThreadLocal弱引用
弱引用比强引用可以多一层保障,弱引用的ThreadLocal会被回收。当忘记调用remove方法时,ThreadLocalMap中以被回收的ThreadLocal为key的value,会在下次ThreadLocalMap调用set、get、remove中的任意方法时将key为null的value也置为null,释放其内存占用,从而避免内存泄露
3. Hash冲突解决
// ThreadLocalMap中计算下标算法,同hashMap下标算法,相当于更高效的取模运算(hashcode % size)
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
// 计算当前ThreadLocal的Hash值
private final int threadLocalHashCode = nextHashCode();
/**
* 提供原子累加、递减操作的Integer类
*/
private static AtomicInteger nextHashCode = new AtomicInteger();
/**
* 特殊hash值
*/
private static final int HASH_INCREMENT = 0x61c88647;
/**
* 原子累加HASH_INCREMENT
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
4. 核心源码
static class ThreadLocalMap {
static class Entry extends WeakReference<ThreadLocal<?>> {
// 当前key为ThreadLocal的value值
Object value;
/**
* entry的key只能时ThreadLocal。
* 继承wakReference,也就是key(ThreadLocal)是弱引用,其目的是将ThreadLocal对象的生命
* 周期和线程的生命周期解绑。
*/
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* 初始容量 -- 必须是2的整次幂.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* 节点数组,长度必须是2的整次幂.
*/
private Entry[] table;
/**
* 数组table中entry的个数,可用于判断table当前使用量是否
*/
private int size = 0;
/**
* 扩容阈值,table中容量大于该阈值时进行扩容
*/
private int threshold;
/**
* 设置扩容阈值为当前数组长度的三分之二
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
/**
* 构造
*/
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
// 初始化数组,默认16
table = new Entry[INITIAL_CAPACITY];
// 计算当前ThreadLocal的下标
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
// 数组对应下标赋值
table[i] = new Entry(firstKey, firstValue);
size = 1;
// 设置数组当前长度的扩容阈值
setThreshold(INITIAL_CAPACITY);
}
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++;
}
}
}
}
// 获取ThreadLocal对应的entry
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);
}
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;
}
// ThreadLocalMap中赋值
private void set(ThreadLocal<?> key, Object value) {
Entry[] tab = table;
int len = tab.length;
// 计算当前ThreadLocal的对应下标
int i = key.threadLocalHashCode & (len-1);
// nextIndex(i,len)判断当前下标i + 1是否越界,当越界时,i = 0,即从数组0再次循环查找
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;
/**
* cleanSomeSlots方法用于清除那些e.get() == null的元素,
* 这种数据key关联的对象已经被回收,所以这个Entry可以被置为null
* 如何没有清除任何entry,并且当前使用量达到了扩容阈值,即进行扩容
*/
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
// 删除对应ThreadLocal
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;
}
}
}
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
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);
}
private int 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;
}
}
}
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;
}
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;
}
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);
}
}
}