ThreadLocal总结
特点
- 抗冲突能力低
- 每个Thread中只能保存一个对应ThreadLocal的一个值
- 由
Thread
中保存变量ThreadLocalMap<ThreadLocal,V>
;
要点
实体继承了·WeakReference·能在不被GCRoot标记时,直接被GC回收
使用类似hash的结构,解决Hash冲突的方法是二次线性探测
一般情况下的hash数组的长度都是2的幂次方,这样是为了位运算
强引用(HardReference)、软引用(softReference)、弱引用(WeakReference)、虚引用(PhantomReference)与GCRoot和GC回收有关系
用途
用于并发程度不高的情况下实现的Session
或者Connection
ThreadLocalMap
static class ThreadLocalMap {
/**
* The entries in this hash map extend WeakReference, using
* its main ref field as the key (which is always a
* ThreadLocal object). Note that null keys (i.e. entry.get()
* == null) mean that the key is no longer referenced, so the
* entry can be expunged from table. Such entries are referred to
* as "stale entries" in the code that follows.
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
/**
* The initial capacity -- MUST be a power of two.
*/
private static final int INITIAL_CAPACITY = 16;
/**
* The table, resized as necessary.
* table.length MUST always be a power of two.
*/
private Entry[] table;
/**
* The number of entries in the table.
*/
private int size = 0;
/**
* The next size value at which to resize.
*/
private int threshold; // Default to 0
/**
* Set the resize threshold to maintain at worst a 2/3 load factor.
*/
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
/**
* Increment i modulo len.
*/
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
/**
* Decrement i modulo len.
*/
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
}