需求场景:每个线程处理任务,存取一些局部变量在当前线程中。
1. ThreadLocal 简单使用:
public static void main(String[] args) {
// 当前线程存入字符串类型
ThreadLocal<String> threadLocal = new ThreadLocal<>();
//1.存入数据
threadLocal.set("sfdfd");
//2.获取数据
String value = threadLocal.get();
System.out.println(value);
//3.最终需要调用remove. 防止内存泄露
threadLocal.remove();
}
2. 下为openjdk17源码:
实现最终是为需求服务的:每个线程存一份自己独有的,可以包涵多个类型数据,数据量不大。
ThreadLocal 数据最终是放入Thread类内部,那么如何放呢。包装下:ThreadLocalMap类就出现了(一个静态内部类)。作用就是存放ThreadLocal数据。使当前线程能保存多个ThreadLocal对象。List也可以存ThreadLocal,但是查找效率不如map
2.1 set方法:
/**
* Sets the current thread's copy of this thread-local variable
* to the specified value. Most subclasses will have no need to
* override this method, relying solely on the {@link #initialValue}
* method to set the values of thread-locals.
*
* @param value the value to be stored in the current thread's copy of
* this thread-local.
*/
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
map.set(this, value);
} else {
// 创建ThreadLocalMap对象。存入第一条数据
// 有参构造方法
createMap(t, value);
}
}
/**
* Get the map associated with a ThreadLocal. Overridden in
* InheritableThreadLocal.
*
* @param t the current thread
* @return the map
*/
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/**
* 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)]) {
if (e.refersTo(key)) {
e.value = value;
return;
}
if (e.refersTo(null)) {
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
2.1.2 上述采用了线性探测法处理hash冲突,他拆开分为了两部分:
# 使用hashcode 对Entry[]数组 取余数,判断放在数组 Entry[]第几个位置
int i = key.threadLocalHashCode & (len-1); # 线性探测,如果获取不到数据则+1 取得下一个位置 private static int nextIndex(int i, int len) { return ((i + 1 < len) ? i + 1 : 0); }
2.1.3 什么是线性探测法:
线性冲突:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。
为什么使用线性冲突而不是像hashMap一样,使用拉链法:
1. 减少内存占用。
2. 简单易实现
3. 适合小规模数据
4. 更好利用cpu缓存 线性探测法使用一个连续的数组来存储数据。当 CPU 访问数组中的某个元素时,缓存不仅会加载该元素,还会预取相邻的几个元素到缓存中
劣势:
hash元素增加,hash冲突多的话,会频繁遍历,导致效率降低
会产生空间分布不均匀
2.2 get()
/**
* Returns the value in the current thread's copy of this
* thread-local variable. If the variable has no value for the
* current thread, it is first initialized to the value returned
* by an invocation of the {@link #initialValue} method.
*
* @return the current thread's value of this thread-local
*/
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();
}
/**
* Get the entry associated with key. This method
* itself handles only the fast path: a direct hit of existing
* key. It otherwise relays to getEntryAfterMiss. This is
* designed to maximize performance for direct hits, in part
* by making this method readily inlinable.
*
* @param key the thread local object
* @return the entry associated with key, or null if no such
*/
private Entry getEntry(ThreadLocal<?> key) {
int i = key.threadLocalHashCode & (table.length - 1);
Entry e = table[i];
//返回的键对象和传入的 key 是否相等
if (e != null && e.refersTo(key))
return e;
else
return getEntryAfterMiss(key, i, e);
}
2.3 remove()
/**
* Removes the current thread's value for this thread-local
* variable. If this thread-local variable is subsequently
* {@linkplain #get read} by the current thread, its value will be
* reinitialized by invoking its {@link #initialValue} method,
* unless its value is {@linkplain #set set} by the current thread
* in the interim. This may result in multiple invocations of the
* {@code initialValue} method in the current thread.
*
* @since 1.5
*/
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null) {
m.remove(this);
}
}
/**
* 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.refersTo(key)) {
e.clear();
// 删除在数组中的元素
// 删除老的entry对象
expungeStaleEntry(i);
return;
}
}
}
/**
* Expunge a stale entry by rehashing any possibly colliding entries
* lying between staleSlot and the next null slot. This also expunges
* any other stale entries encountered before the trailing null. See
* Knuth, Section 6.4
*
* @param staleSlot index of slot known to have null key
* @return the index of the next null slot after staleSlot
* (all between staleSlot and this slot will have been checked
* for expunging).
*/
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;
}
3. 思考
3.1 ThreadLocal 有意思地方,ThreadLocal最终存放在了Thread类内部,用ThreadLocalMap进行接收。ThreadLocalMap是ThreadLocal的一个静态内部类。Thread 有个threadLocals 对象 类型就是ThreadLocalMap
3.2 使用了线性探测来解决hash冲突问题。线性探测就是hash对数组长度取余后,如果发生冲突,那么则对当前槽位循环,每次加1
3.3 弱引用理解:
ThreadLocalMap的key 为threadlocal 且为弱引用. 我自己的理解为thread短暂时间内不会被回收,但是又想threadlocal在不使用以后把他干掉,所以使用了弱引用。
如果将ThreadLocalMap的key设置为强引用,使用完以后,是需要等待当前线程对象被销毁,他的ThreadLocalMap, ThreadLocal才会被删除。主要就是因为对象内套了一层又一层。又想把最里面的对象给优化掉,所以才为弱引用。当ThreadLocal被回收后,ThreadLocalMap也会判断当前key是否存在,如果不存在value也置空干掉。
3.4 ThreadLocalMap 扩容:
3.4.1 ThreadLocal的set方法截取最后扩容部分:
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
3.4.2 rehash()方法
/**
* Re-pack and/or re-size the table. First scan the entire
* table removing stale entries. If this doesn't sufficiently
* shrink the size of the table, double the table size.
*/
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
3.4.3 resize()
/**
* Double the capacity of the table.
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
//扩容为原数组的两倍
int newLen = oldLen * 2;
Entry[] newTab = new Entry[newLen];
int count = 0;
for (Entry e : oldTab) {
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;
}
3.4.4 初始Entry[]数组为16 . 扩容阈值为容量的2/3. 扩容的倍数为2。如果当前数组为16,那么扩容后为32
/** * The initial capacity -- MUST be a power of two. */ private static final int INITIAL_CAPACITY = 16;/** * Set the resize threshold to maintain at worst a 2/3 load factor. */ private void setThreshold(int len) { threshold = len * 2 / 3; }
4. 以上为我的思考,有机会再补几张图。个人水平有限,上述如有错误欢迎指正修改!