ThreadLocal源码分析
2020-01-09 本文已影响0人
spring_coderman
ThreadLocal-field.png
ThreadLocal.png
ThreadLocal-method.png
ThreadLocal变量.png
getcreate方法.jpg
remove方法.jpg
threadLoalMap数据结构.jpg
threadLocalget方法.jpg
ThreadlocalMap的方法.jpg
threadlocalset方法.jpg
ThreadLocalMap的构造方法
/**
* Construct a new map initially containing (firstKey, firstValue).
* ThreadLocalMaps are constructed lazily, so we only create
* one when we have at least one entry to put in it.
*/
ThreadLocalMap(ThreadLocal firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY];
//通过当前ThreadLocal对象的hash码和对应容量大小找到对应的entry位置
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
//由于一开始初始化并没有设置其加载因子,因此在初始化之后需要设置一下
setThreshold(INITIAL_CAPACITY);
}
/**
* Construct a new map including all Inheritable ThreadLocals
* from given parent map. Called only by createInheritedMap.
*
* @param parentMap the map associated with parent thread.
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
//这里这个方法为了兼容从父类中获取其线程本地变量而写的另一个构造方法
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
//先确定加载因子,
setThreshold(len);
//初始化当前线程本地变量的entry数组长度
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
ThreadLocal key = e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
//这里如果有冲突就找下一个entry所在的数组下标,用的是开放定址法/线性探测法
while (table[h] != null)
h = nextIndex(h, len);
//找到下一个entry为空的数组位置然后初始化
table[h] = c;
size++;
}
}
}
}
ThreadLocalMap的get方法
/**
* 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];
if (e != null && e.get() == key)
return e;
else
//注意这里的get一旦获取不到可能是已经失效了,需要做进一步的处理确定已经失效了
return getEntryAfterMiss(key, i, e);
}
/**
* Version of getEntry method for use when key is not found in
* its direct hash slot.
*
* @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();
//这里的k有引用的,因此即使value是被设置为空,也可能不会被回收,因此是导致内存溢出的一个原因《》
if (k == key)
return e;
if (k == null)
//如果entry数组中某个key为空,说明entry的内容不是最新的,因此需要过滤掉脏数据
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
//如果找不到说明已经失效了或者被回收了
return null;
}
/**
* 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).
*/
//通过这里的入参名称可以知道在entry的staleSlot位置上的元素是过期的脏数据
//这里的清除相当于手动设置空,保证当前entry数组里是最新的数据,至于设置为空的entry相当于没有引用指向他了,
//所以会通过jvm回收
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
//将整个entry的k,v都设置为空
// expunge entry at staleSlot
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
//由于entry的某个位置出现了空值,我们需要重新hash一下,保持一定的分布
//另一方面由于之前已经有旧数据了,通过rehash我们可以找到其他旧的脏数据
// 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) {
//这里说明其他的entry已经是脏数据了,同样需要设置空
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);
//重新调整entry里元素的位置
tab[h] = e;
}
}
}
//由于上面已经在rehash过程中重新组织了数据,所以这里返回的是miss之后新的entry元素下标
return i;
}
ThreadLocalMap的set方法
/**
* 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)]) {
ThreadLocal k = e.get();
//找到Key更新 value,返回
if (k == key) {
e.value = value;
return;
}
if (k == null) {
//有可能数据已经是脏数据了,从脏数据中的entry数组中更新
replaceStaleEntry(key, value, i);
return;
}
}
tab[i] = new Entry(key, value);
int sz = ++size;
if (!cleanSomeSlots(i, sz) && sz >= threshold)
rehash();
}
/**
* Replace a stale entry encountered during a set operation
* with an entry for the specified key. The value passed in
* the value parameter is stored in the entry, whether or not
* an entry already exists for the specified key.
*
* As a side effect, this method expunges all stale entries in the
* "run" containing the stale entry. (A run is a sequence of entries
* between two null slots.)
*
* @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;
// 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;
//更新整个entry
tab[staleSlot] = new Entry(key, value);
// If there are any other stale entries in run, expunge them
//找到其他过期的entry
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
/**
* Heuristically scan some cells looking for stale entries.
* This is invoked when either a new element is added, or
* another stale one has been expunged. It performs a
* logarithmic number of scans, as a balance between no
* scanning (fast but retains garbage) and a number of scans
* proportional to number of elements, that would find all
* garbage but would cause some insertions to take O(n) time.
*
* @param i a position known NOT to hold a stale entry. The
* scan starts at the element after i.
*
* @param n scan control: <tt>log2(n)</tt> cells are scanned,
* unless a stale entry is found, in which case
* <tt>log2(table.length)-1</tt> additional cells are scanned.
* When called from insertions, this parameter is the number
* of elements, but when from replaceStaleEntry, it is the
* table length. (Note: all this could be changed to be either
* more or less aggressive by weighting n instead of just
* using straight log n. But this version is simple, fast, and
* seems to work well.)
*
* @return true if any stale entries have been removed.
*/
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;
}
ThreadLocalMap的remove方法
/**
* 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) {
//这里的清空走的是Reference接口的清空方法,但是整个数组的大小并没有变化
e.clear();
//清空之后这个entry数组就存在脏数据了,因此需要处理,这里的处理是不依赖JVM回收的,因此要主动回收
expungeStaleEntry(i);
return;
}
}
}
ThreadLocalMap的rehash/resize方法
/**
* 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() {
//1.先进行一轮脏数据的清除
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
//这句话的意思是使用较低的加载因子去判定是否需要扩容到两倍的数组大小,
//这么做的原因是避免数据新增较快,扩容频率跟不上
if (size >= threshold - threshold / 4)
resize();
}
/**
* Double the capacity of the table.
*/
private void resize() {
Entry[] oldTab = table;
int oldLen = oldTab.length;
//数组大小直接扩容为2倍
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();
//由于在扩容过程中仍然存在k为null的情况,这里在扩容的时候将value也设置为空,那么
当前这个entry对象也相当于是脏数据了,后面会被更新为新数据
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;
}
ThreadLocal总结:
- ThreadLocal是Thread拥有的线程变量副本的实现,提供一些init/get/set/remove接口。
- ThreadLocal通过ThreadLocalMap实现线程副本的存储,其简单实现了数组链表来存储kv键值对的数据结构
- ThreadLocal被很多框架使用,是作为多线程编程的一个常用的技术
- ThreadLocal使用不当会存在内存溢出和脏数据的问题
- ThreadLocal主要用于同一个线程内跨类,跨方法传递数据,也可以用于透传全局上下文需要使用的一些变量
- 使用上推荐声明为private static final ThreadLocal<T>
- ThreadLocal这里是基于1.7阅读的,1.8增加了一些函数式方法,不做过多分析
- 另外可参考《码出高效-Java开发手册》
相关链接:
https://www.cnblogs.com/dennyzhangdd/p/7978455.html
https://www.jianshu.com/p/80866ca6c424