Question

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.

Was it helpful?

Solution

Notice how all these variables are declared static. That means there is normally only ever one.

To make threadId thread specific we use threadlocal. Which means instead of there being one instance there will now be one instance per thread.

In your version each time we call get() it will return a different number.

In the original version the first time get is called it will initialise itself and save the value on the thread. This value will be returned for each subsequent call to get on that thread.

your code

//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 2
//in thread 1
ThreadId.get() //return 3
//in thread 0
ThreadId.get() //return 4

original code

//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 0
//in thread 1
ThreadId.get() //return 1
//in thread 0
ThreadId.get() //return 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top