ThreadLocal平时用的比较多,通过将变量在每个线程放一个副本,避免了在多线程下对于变量的争抢。
ThreadLocal源码比较简单,整体了解起来比较容易。
static class ThreadLocalMap {
ThreadLoca维护了内部类ThreadLocalMap。
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;
}
ThreadLocal.ThreadLocalMap threadLocals = null;
可以发现通过线程获取一个ThreadLocalMap,而值的获取通过this(就是ThreadLocal)获取一个Entry。
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);
}
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
table = new Entry[INITIAL_CAPACITY]; int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
数据放在ThreadLocalMap中,key是ThreadLocal。
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread()); if (m != null)
m.remove(this);
} 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) {
e.clear();
expungeStaleEntry(i); return;
}
}
}
ThreadLocal核心代码就这么多吧,主要关注下里面的Entry,ThreadLocalMap。