Java Thread Tutorial - Java Thread-Local Variables

A thread-local variable separates value for a variable for each thread.

The ThreadLocal class in the java.lang package provides the implementation of a thread-local variable.

It has four methods: get(), set(), remove(), and initialValue().

The get() and set() methods are used to get and set the value for a thread-local variable, respectively.

You can remove the value by using the remove() method.

The initialValue() method sets the initial value of the variable, and it has a protected access. To use it, subclass the ThreadLocal class and override this method.


The following code shows how to use ThreadLocal class.

public class Main {
  public static void main(String[] args) {
    new Thread(Main::run).start();
    new Thread(Main::run).start();
  }//from w  w  w . j ava2  s  .  c om
  public static void run() {
    int counter = 3;
    System.out.println(Thread.currentThread().getName()+ "  generated counter:  " + counter);
    for (int i = 0; i < counter; i++) {;
class CallTracker {
  private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
  public static void call() {
    int counter = 0;
    Integer counterObject = threadLocal.get();

    if (counterObject == null) {
      counter = 1;
    } else {
      counter = counterObject.intValue();
    String threadName = Thread.currentThread().getName();
    System.out.println("Call  counter for " + threadName + "  = " + counter);

The code above generates the following result.