ThreadLocalMap是ThreadLocal的内部类,核心操作都在ThreadLocalMap类里实现
当我们在外部通过ThreadLocal对象调用get方法获得在之前传入的value,本质上是取出当前线程Thread对象的ThreadLocalMap对象,再从中取出想要的值,也就意味着ThreadLocalMap是线程私有的。
因为对ThreadLocalMap的操作封装在内部,由ThreadLocal提供对外接口,完美的体现了Java封装性,这样其它线程就无法访问本线程的ThreadLocalMap,所以说是线程安全的。
每个Thread对象都有两个ThreadLocalMap成员
//Thread类里涉及到ThreadLocal的东西
ThreadLocal.ThreadLocalMap threadLocals = null;
ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
...
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
...
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
private void exit() {
...
threadLocals = null;
inheritableThreadLocals = null;
...
}
InheritableThreadLocal类是ThreadLocal的子类,并重写了父类的三个方法。当Thread线程创建子线程时,子线程可以继承父线程的inheritableThreadLocals
public class InheritableThreadLocal<T> extends ThreadLocal<T> {
protected T childValue(T parentValue) {
return parentValue;
}
ThreadLocalMap getMap(Thread t) {
return t.inheritableThreadLocals;
}
void createMap(Thread t, T firstValue) {
t.inheritableThreadLocals = new ThreadLocalMap(this, firstValue);
}
}
ThreadLocalMap
基本成员:
static class ThreadLocalMap {
/*Entry对象使用弱引用,内部引用指向ThreadLocal对象,同时成员value指向用户value
*使用弱引用是为了方便GC,当ThreadLocal对象被回收时,调用entry.get()方法
*就知道所指向得到对象是否被回收,那么就可以直接删除该Entry。
*但还是建议在该value使用结束后,外部显示的调用remove方法移除该Entry,因为Entry
*成员value使用的强引用,在使用线程池的情况下线程的生命周期较长,即使threadlocal
*被回收,若之后执行的任务一直没有使用threadLocalMap,那么threadLocalMap就不会
*删除废弃的Entry,value一直保持强引用,导致GC无法回收无用内存,造成内存泄露。
*/
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
private static final int INITIAL_CAPACITY = 16;
private Entry[] table;
private int size = 0;
private int threshold; // Default to 0
private void setThreshold(int len) {
threshold = len * 2 / 3;
}
//采用循环数组的方式,若i为数组最后一个则返回第一个
private static int nextIndex(int i, int len) {
return ((i + 1 < len) ? i + 1 : 0);
}
private static int prevIndex(int i, int len) {
return ((i - 1 >= 0) ? i - 1 : len - 1);
}
构造方法:
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
//ThreadLocal的类变量private static final int INITIAL_CAPACITY = 16;
table = new Entry[INITIAL_CAPACITY];
//private static AtomicInteger nextHashCode = new AtomicInteger();
//散列码是ThreadLocal的类变量,初值从0x61c88647开始,每次获得前自加一
int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
table[i] = new Entry(firstKey, firstValue);
size = 1;
setThreshold(INITIAL_CAPACITY);
}
/**
* 此方法是用来继承父线程的inheritableThreadLocalMap
* 可以通过重写childValue方法来标记value
*/
private ThreadLocalMap(ThreadLocalMap parentMap) {
Entry[] parentTable = parentMap.table;
int len = parentTable.length;
setThreshold(len);
table = new Entry[len];
for (int j = 0; j < len; j++) {
Entry e = parentTable[j];
if (e != null) {
@SuppressWarnings("unchecked")
ThreadLocal<Object> key = (ThreadLocal<Object>) e.get();
if (key != null) {
Object value = key.childValue(e.value);
Entry c = new Entry(key, value);
int h = key.threadLocalHashCode & (len - 1);
while (table[h] != null)
h = nextIndex(h, len);
table[h] = c;
size++;
}
}
}
}
set方法:
//通过key的哈希值找到在数组中的下标,若符合则赋值后返回
//若该位置为空,这新建一个entry放入并判断是否应该扩容
//若entry.get为null则表明该entry废弃,调用replaceStaleEntry(key, value, i)
private void set(ThreadLocal<?> key, Object value) {
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();
}
private void replaceStaleEntry(ThreadLocal<?> key, Object value,
int staleSlot) {
Entry[] tab = table;
int len = tab.length;
Entry e;
//向前找尽可能清理更多废弃的entry
//因为table只会使用四分之三的空间,因此可以保证循环停止
int slotToExpunge = staleSlot;
for (int i = prevIndex(staleSlot, len);
(e = tab[i]) != null;
i = prevIndex(i, len))
if (e.get() == null)
slotToExpunge = i;
//试图向后找,是否有entry与key指向相同
for (int i = nextIndex(staleSlot, len);
(e = tab[i]) != null;
i = nextIndex(i, len)) {
ThreadLocal<?> k = e.get();
//若找到相同,则交换废弃entry和该entry
if (k == key) {
e.value = value;
tab[i] = tab[staleSlot];
tab[staleSlot] = e;
//交换之后判断清理开始位置,若和staleSlot相同,则直接从i开始清理
if (slotToExpunge == staleSlot)
slotToExpunge = i;
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
return;
}
if (k == null && slotToExpunge == staleSlot)
slotToExpunge = i;
}
//若未找到,则直接替换
tab[staleSlot].value = null;
tab[staleSlot] = new Entry(key, value);
//若有需要清理的废弃entry则进行清理
if (slotToExpunge != staleSlot)
cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
}
/*执行log2(n)次清理以取得清理效果(剩余废弃entry数量)和清理耗时之间的平衡。
* 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
*/
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;
}
//真正移除entry的方法
private int expungeStaleEntry(int staleSlot) {
Entry[] tab = table;
int len = tab.length;
tab[staleSlot].value = null;
tab[staleSlot] = null;
size--;
//遍历后序entry,若废弃,则置为null帮助GC
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 {
//可能前面的被清除,将该entry放入最靠前的哈希槽
int h = k.threadLocalHashCode & (len - 1);
if (h != i) {
tab[i] = null;
while (tab[h] != null)
h = nextIndex(h, len);
tab[h] = e;
}
}
}
return i;
}
在set方法的最后,会清理一次table,若此次清理废弃entry数量为0并且size大于等于threshold就进行扩容判断
//在扩容前会进行一次全数组清理,若结果依然大于threshold的3/4则进行扩容
private void rehash() {
expungeStaleEntries();
// Use lower threshold for doubling to avoid hysteresis
if (size >= threshold - threshold / 4)
resize();
}
private void expungeStaleEntries() {
Entry[] tab = table;
int len = tab.length;
for (int j = 0; j < len; j++) {
Entry e = tab[j];
if (e != null && e.get() == null)
expungeStaleEntry(j);
}
}
//扩容至原来的两倍
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++;
}
}
}
get方法:
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
return getEntryAfterMiss(key, i, e);
}
//若entry指向和key相同则返回,若为废弃entry则进行清理
private Entry getEntryAfterMiss(ThreadLocal<?> key, int i, Entry e) {
Entry[] tab = table;
int len = tab.length;
while (e != null) {
ThreadLocal<?> k = e.get();
if (k == key)
return e;
if (k == null)
expungeStaleEntry(i);
else
i = nextIndex(i, len);
e = tab[i];
}
return null;
}
remove方法
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(); //将弱引用置为null,帮助GC
expungeStaleEntry(i);
return;
}
}
}
ThreadLocal
set方法
//看懂上边理解这就非常简单
//从当前线程中取的threadLocalMap并以当前threadLocal(this)为键,value为值设置
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
//若threadLocalMap为null,则创建一个新的threadLocalMap
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
get方法
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();
}
private T setInitialValue() {
T value = initialValue(); //返回null,也可以自己继承并重写
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
remove方法
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}