Search code examples
javamultithreadingthread-local

Threadlocal variable coming out to be null


I am trying to print threadlocal variable in the run method via thread execution but it is apparently coming out to be null. Please find the code for info ---

public class EvenAndOdd implements Runnable{

public EvenAndOdd() {

}

public  static void setThreadContext(){
 threadLocal.set(3);
 eventhreadLocal.set(2);
}
 private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
 private static ThreadLocal<Integer> eventhreadLocal = new ThreadLocal<Integer>(); 

@Override
public void run() {
    System.out.println(threadLocal.get());
    System.out.println(eventhreadLocal.get());
}

}

// Now the class for creating the thread and calling the run method

public class PrintNumber {
public static void main(String[] args) {

    EvenAndOdd evenAndOdd =new EvenAndOdd();
    EvenAndOdd.setThreadContext();
    Thread printThread = new Thread(evenAndOdd);
    printThread.start();

}
}

Problem statement --- execution of the thread is giving me null rather than 2 & 3


Solution

  • You are observing the behavior which is the whole point of the ThreadLocal: what you set in one thread is not visible from another. You must set the ThreadLocal values from within the thread where you use them.