public class DemoApp {
private static final AtomicInteger nextIndex = new AtomicInteger();
public static final int VARIABLES_TO_REMOVE_INDEX = nextVariableIndex();
public static int nextVariableIndex() {
return nextIndex.getAndIncrement();
}
public static void main(String[] args) {
System.out.println(VARIABLES_TO_REMOVE_INDEX);
System.out.println(VARIABLES_TO_REMOVE_INDEX);
System.out.println(VARIABLES_TO_REMOVE_INDEX);
System.out.println(VARIABLES_TO_REMOVE_INDEX);
}
}
上面这段代码其实摘抄自 netty InternalThreadLocalMap
public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap {
private static final ThreadLocal[I] slowThreadLocalMap =
new ThreadLocal[I]();
private static final AtomicInteger nextIndex = new AtomicInteger();
// Internal use only.
public static final int VARIABLES_TO_REMOVE_INDEX = nextVariableIndex();
private static final int DEFAULT_ARRAY_LIST_INITIAL_CAPACITY = 8;
public static int nextVariableIndex() {
int index = nextIndex.getAndIncrement();
if (index >= ARRAY_LIST_CAPACITY_MAX_SIZE || index
因为看到网上都说 InternalThreadLocalMap 存储元素的数组 0 号位置是一个类型为 set 的元素,所以对这段代码有点疑惑,那为什么 VARIABLES_TO_REMOVE_INDEX 不直接写 0 ?