think in java - concurrency - ThreadLocal

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

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.

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

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


你可能感兴趣的:(think in java - concurrency - ThreadLocal)