This is the example in java doc for the ThreadLocal use.
public class ThreadId { // Atomic integer containing the next thread ID to be assigned private static final AtomicInteger nextId = new AtomicInteger(0); // Thread local variable containing each thread's ID private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() { @Override protected Integer initialValue() { return nextId.getAndIncrement(); } }; // Returns the current thread's unique ID, assigning it if necessary public static int get() { return threadId.get(); } } i dont get the point that why we used threadlocal here. isnt AtomicInteger already thread safe?
what about changed the code to this?
public class ThreadId { // Atomic integer containing the next thread ID to be assigned private static final AtomicInteger nextId = new AtomicInteger(0); // Returns the current thread's unique ID, assigning it if necessary public static int get() { return nextId.getAndIncrement(); } } I also dont get what this means:
These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
So, is ThreadLocal (internally) holds an array of integer for each thread? the Java_concurrency in practice mentioned that we can consider threadLocal as Map.
Thanks in advanced.