ThreadLocal详解
构建了一个类,它具有begin() 和 end()两个方法,而end()方法返回从begin()方法调用开始到end()方法被调用的时间差。
import java.util.concurrent.TimeUnit;
public class MyThread07 {
private static final ThreadLocal TIME_THREADLOCAL = new ThreadLocal<>() {
protected Long initialValue() {
return System.currentTimeMillis();
}
};
public static final void begin() {
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
public static final long end() {
return System.currentTimeMillis() - TIME_THREADLOCAL.get();
}
public static void main(String[] args) throws InterruptedException {
MyThread07.begin();
TimeUnit.SECONDS.sleep(1);
System.out.println("Cost: " + MyThread07.end() + "mills");
}
}
ThreadLocal,也叫线程变量,是一个以ThreadLocal对象为键、任意对象那个为值的存储结构,这个结构被附带在线程上,也就是说,一个线程可以根据一个ThreadLocal对象查询到绑定在这个线程上的值。
可以通过set(T)来设置一个值,当前线程下再通过get()来获取原先设置的值。如上述代码所示。
源码
我们下面通过ThreadLocal的源码来解析ThreadLocal
ThreadLocal的三个理论基础:
ThreadLocal有三个方法get(), set(T),remove()。我们来分析这三个方法:
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 getMap(Thread t) {
return t.threadLocals;
}
ThreadLocal.ThreadLocalMap threadLocals = null;
createMap(Thread t, T firstvalue)
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);
}
private static final int INITIAL_CAPACITY = 16;
private final int threadLocalHashCode = nextHashCode();
private static int nextHashCode() {
return nextHashCode.getAndAdd(HASH_INCREMENT);
}
private static AtomicInteger nextHashCode = new AtomicInteger();
我们发现,ThreadLocalMap其实使用的是开放地址法,设置table中的位置时,都把一个静态的nextHashCode雷加一下,说明,set的同一个value,在每个线程中的ThreadLocalMap位置是不一样的,但其实并不重要。
我们再来看一下设置的分支
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();
}
1、先对ThreadLocal里面的threadLocalHashCode取模获取到一个table中的位置
2、这个位置上如果有数据,获取这个位置上的ThreadLocal
(1)判断一下位置上的ThreadLocal和我本身这个ThreadLocal是不是一个ThreadLocal,是的话数据就覆盖,返回
(2)不是同一个ThreadLocal,replaceStaleEntry(key, value, i),再判断一下位置上的ThreadLocal是不是空的,Entry是ThreadLocal弱引用,有可能这个ThreadLocal被垃圾回收了,这时候把新设置的value替换到当前位置上,返回
3、这个位置上如果没有数据,给模加1,看看模加1后的table位置上是不是空的,是空的再加1,判断位置上是不是空的,一直到找到一个table上的位置不是空的为止,往这里面塞一个value。
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 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);
}
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;
}
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;
}
}
}
public void clear() {
this.referent = null;
}
取得当前线程的ThreadLocal.ThreadLocalMap,如果有,找到对应的Entry,移除掉就好了。