分析ThreadLocalMap源码的原因,是想看看使用WeakReference的类似Map数据结构是如何销毁已被回收的WeakReference指向的对象。了解销毁的算法,学习其思路,以备以后自己开发类似功能。
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
Entry[] table; // 这是ThreadLocalMap保存数据的地方。
table[i].get();获取的是WeakReference指向的值,而不是value。这个值会在除WeakReference外,没有其他引用指向的时候,被JVM回收。
问题提出:
如果WeakReference指向的值,即ThreadLocal,被JVM回收后(常见是,在Thread结束后的一次gc)。table不错陈旧数据处理,会怎么样?答案是table无限增大,效率随时间的增长不断的降低。如何高效的回收,是学习的重点。
private int expungeStaleEntry(int staleSlot);如果发现table一个slot,使得table[slot].get() == null。表明数据陈旧,需回收。调用该方法。
代码:
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;
}
不仅将当前slot的Entry置空,还要检查slot到下一个为null的slot之间的entry。如果为陈旧的数据,则置空。如果不是,进行rehash。
rehash的原理是:int h = k.threadLocalHashCode & (len - 1); h!=i,表明当初在新增的时候,就发生了hash冲突,导致该entry在table的位置后移。处理方式是:将tab[i]=null,重新找index为h及之后的table,直道找到table[h]=null,然后将table[h] = e。hash冲突会随后介绍。
返回值是下一个table[slot]==null的slot;
private boolean cleanSomeSlots(int i, int n)。这个函数实际是调用expungeStaleEntry清除陈旧数据的。
代码:
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;
}
比较有意思的是这句:while ( (n >>>= 1) != 0); 循环log2(n)次,目的是平衡不做清除(高效但是陈旧数据残留)和全部判断并做清除(对一些插入操作性能造成影响)。这种做法目前挺高效,并且工作挺不错,所以就用着了。
if (e != null && e.get() == null) { n = len; 意味着一旦发现有陈旧数据,循环次数将增加。
返回值,是否有陈旧值被清除。
private void set(ThreadLocal
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();
}
有了上面的介绍,这段就很好理解了。replaceStaleEntry(key, value, i);这句以后再研究,有点复杂(向前去除陈旧数据)。
这句有点意思:
if (!cleanSomeSlots(i, sz) && sz >= threshold) rehash(); 如果有陈旧值被处理,那么一定不会进行rehash。如果没有陈旧值被删除,则看当前table的entry数量是否大于阈值。是,则rehash。
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
清除所有陈旧值,然后resize。
rezie()有点意思,处理hash冲突的方式和HashMap不一样。
代码:
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;
}
将新的table大小设为旧的table大小的2倍。然后将旧的table中entry挨个插入到新的table中,当然,插入前还是要判断entry是否过期。
插入过程中,如果发现hash冲突(int h = k.threadLocalHashCode & (newLen - 1); ),则查找h之后的table元素,知道table[h] != null,将table[h] = e;
这应该是另一种hash探测法吧,还得找时间学学。
对比WeakHashMap,大致原理与ThreadLocalMap相似。
WeakHashMap执行expungeTableEntries()是在resize(), size(), getTable()等方法中。而不是在每一次插入。