1. 程式人生 > >netty原始碼閱讀之效能優化工具類之FastThreadLocal的建立

netty原始碼閱讀之效能優化工具類之FastThreadLocal的建立

建立的話我們直接從FastThreadLocal的構造方法進入:

    public FastThreadLocal() {
        index = InternalThreadLocalMap.nextVariableIndex();
    }

可見他是現在這裡建立了index,這個index就是每個執行緒裡面FastThreadLocal唯一的標識。

看這個nextVariableIndex()方法:

    public static int nextVariableIndex() {
        int index = nextIndex.getAndIncrement();
        if (index < 0) {
            nextIndex.decrementAndGet();
            throw new IllegalStateException("too many thread-local indexed variables");
        }
        return index;
    }

next是什麼呢?

    static final AtomicInteger nextIndex = new AtomicInteger();

所以沒什麼好說的,就是每次新建一個FastThreadLocal執行緒裡面的index都會加1,這個index作為這個新建FastThreadLocal的標識,以後要找到這個FastThreadLocal就通過這個標識。

那麼在什麼地方找到這個FastThreadLocal呢?後面我們會知道,這裡會有一個數組,可以通過FastThreadLocal的index找到這個FastThreadLocal物件在數組裡面的位置。