DefaultThreadFactory在创建线程时默认使用的是FastThreadLocalThread,那么为什么叫Fast呢?
普通的线程中都有一个线程私有的ThreadLocal.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();
}
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);
}
可以看到第15行使用的是与运算得到数组下标。
FastThreadLocalThread内部有一个InternalThreadLocalMap,看一下它的get()
public static InternalThreadLocalMap get() {
Thread thread = Thread.currentThread();
if (thread instanceof FastThreadLocalThread) {
return fastGet((FastThreadLocalThread) thread);
} else {
return slowGet();
}
}
private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) {
InternalThreadLocalMap threadLocalMap = thread.threadLocalMap();
if (threadLocalMap == null) {
thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap());
}
return threadLocalMap;
}
private static InternalThreadLocalMap slowGet() {
ThreadLocal<InternalThreadLocalMap> slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap;
InternalThreadLocalMap ret = slowThreadLocalMap.get();
if (ret == null) {
ret = new InternalThreadLocalMap();
slowThreadLocalMap.set(ret);
}
return ret;
}
如果是slowGet,那么就是把InternalThreadLocalMap放到了原来的ThreadLocal里。
如果是fastGet,那么就把FastThreadLocalThread内部的InternalThreadLocalMap直接返回,如果为空就创建一个新的。
原来这就是比 ThreadLocal 更快的玩意? - 掘金原来这就是比 ThreadLocal 更快的玩意? - 掘金原来这就是比 ThreadLocal 更快的玩意? - 掘金