Contents

一个线程单独的开放寻址探测的hashmap,本地存储变量,每个线程不共享变量,就没有了并发问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private final int threadLocalHashCode = nextHashCode();

/**
* The next hash code to be given out. Updated atomically. Starts at
* zero.
*/
private static AtomicInteger nextHashCode =
new AtomicInteger();

/**
* The difference between successively generated hash codes - turns
* implicit sequential thread-local IDs into near-optimally spread
* multiplicative hash values for power-of-two-sized tables.
*/
private static final int HASH_INCREMENT = 0x61c88647;

/**
* Returns the next hash code.
*/
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}

ThreadLocal里面有这个几个内部变量,threadLocalHashCode是这个线程本地的hashCode值,这个值是取nextHashCode这个原子变量,初始值是0,每次递增HASH_INCREMENT。就是说每个线程从创建依次递增0x61c88647,这个数据很有来头,是32位有符号数字的黄金比例,为了让hash值能更好的分散,不出现冲突。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}

每个线程thread里有一个变量是threadLocals,通过当前threadlocal对象为key,获取存储的ThreadLocalMap,里面的value,就是我们存储的变量。

1
2
3
4
5
6
7
8
9
10
11
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}

Set方法跟get原理差不多,主要是这个ThreadLocalMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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;

可以看出来这个ThreadLocal的内部类ThreadLocalMap,里面有一个Entry是弱引用ThreadLocal,Entry强引用value。ThreadLocalMap是使用数组作为底层的存储结构。我当时还想为什么没有继承hashmap,原来是hash算法不一致,hashmap使用拉链法解决冲突,而这里使用的开放寻址法,这种算法在大量冲突的时候,效率比较低,但我们前面提到的hashcode算法,有效的让hash值不特别冲突,而且本地变量应该与hashmap这样的数据结构不一样,没有那么大的存储量级,所以这样效率更高。

总结:基于数组存储的,开放寻址法的哈希散列。每个散列值存储在线程本地,通过ThreadLocal代理去线程内获取变量。
这次先看总的结构,还有些里面的清理方法没有完全看懂,下次继续。

Contents