think in java - concurrency - ThreadLocal

ThreadLocal storage is a mechanism that automatically creates different storage for each different thread.java

private static ThreadLocal<Integer> value = new ThreadLocal<Integer>(){
    private Random random = new Random(47);
    protected Integer initialValue() {
        return random.nextInt(10000);
    };
};

# access the value
value.get()

# set the value
value.set(value.get() + 1);


ThreadLocal objects are usually stored as static fields.dom

Inside the ThreadLocal, there is a 'hash map' ThreadLocalMap which is static, hence every threadlocal instance will access the same map. 
ide

Inside the map, key is threadlocal object and value is the one stored within that threadlocal.code

相關文章
相關標籤/搜索