netty觉得java中的ThreadLocal不好用,于是就又搞了一套类似的“产品”:「FastThreadLocal」,你还可以发现其他几个定义:PoolThreadLocalCache,PoolThreadCache,FastThreadLocalThread,InternalThreadLocalMap,一套组合拳下来,直呼厉害的同时,也晕了。其他这些都是和「ThreadLocal」类似的一些定义。
FastThreadLocal和 ThreadLocal 相关的对比
PoolThreadLocalCache为FastThreadLocal的实现,override了initialValue()方法,实例化netty相关的PoolThreadCache,它主要是注入了poolArea相关属性,在分配内存时使用。由图可以看到InternalThreadLocalMap为FastThreadLocal整个“套餐”核心。
InternalThreadLocalMap
首先看下相关定义:
public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap {
public static int nextVariableIndex() {
int index = nextIndex.getAndIncrement();
if (index < 0) {
nextIndex.decrementAndGet();
throw new IllegalStateException("too many thread-local indexed variables");
}
return index;
}
}
class UnpaddedInternalThreadLocalMap {
static final AtomicInteger nextIndex = new AtomicInteger();
Object[] indexedVariables;
}
在InternalThreadLocalMap保存属性用了一个Object数组,这个是不同于ThreadLocalMap的Map.Entry实现:
static class Entry extends WeakReference<ThreadLocal<?>> {
/** The value associated with this ThreadLocal. */
Object value;
Entry(ThreadLocal<?> k, Object v) {
super(k);
value = v;
}
}
在threadlocalMap中可以通过不同的ThreadLocal实例来区分不同的属性值,对于这个Object数组是怎样进行区分的呢?
FastThreadLocal
private final int index;
public