I was implementing a Thread Local example using following code, I thought I'd be getting random numbers in the output but when the threadLocal.get()
method is called I get a zero for all threads n output, am I missing something here. Here is my code and the output, will deeply appreciate the help. Thanks in advance.
package concurrency;
public class ThreadLocalExample {
public static void main(String[] args) throws InterruptedException {
SubLocalClass subLocalClass = new SubLocalClass();
for(int i=0;i<10;i++) {
Thread thread = new Thread(subLocalClass);
thread.start();
thread.join();
}
}
}
class SubLocalClass implements Runnable{
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 1000;
}
};
@Override
public void run() {
threadLocal.set((int) Math.random());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getId()+" "+
Thread.currentThread().getName()+" "+threadLocal.get());
}
}
And the output that I am getting is this
12 Thread-0 0
13 Thread-1 0
14 Thread-2 0
15 Thread-3 0
16 Thread-4 0
17 Thread-5 0
18 Thread-6 0
19 Thread-7 0
20 Thread-8 0
21 Thread-9 0
why 0
for threadLocal.get()
for all the threads, shouldn't it be publishing random numbers?
Thanks for your help on this.
You set the thread local to zero:
threadLocal.set((int) Math.random());
Because Math.random()
returns a double between 0
and 1
, when you cast it to an int it will yield 0
.