Java - Thread-Local Variables

Introduction

A thread-local variable is a unique separated variable for each thread.

ThreadLocal class from java.lang package implements of a thread-local variable.

Method Description
get() get the value for a thread-local variable
set() set the value for a thread-local variable
remove()remove the value
initialValue() set the initial value of the variable. It has a protected access. To use it, you need to subclass the ThreadLocal class and override this method.

A Class That Uses a ThreadLocal Object to Track Calls to Its Method

Demo

class CallTracker {
  private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();

  public void call() {
    int counter = 0;
    Integer counterObject = threadLocal.get();

    if (counterObject == null) {
      counter = 1;//from   w  w  w .ja v  a2 s .co  m
    } else {
      counter = counterObject.intValue();
      counter++;
    }

    // Set the new counter
    threadLocal.set(counter);

    // Print how many times this thread has called this method
    String threadName = Thread.currentThread().getName();
    System.out.println("Call counter for " + threadName + " = " + counter);
  }
}

public class Main {
  public static void main(String[] args) {
    // Let's start three threads to the CallTracker.call() method
    new Thread(Main::run).start();
    new Thread(Main::run).start();
    new Thread(Main::run).start();
  }

  public static void run() {

    int counter = 5;
    // Print the thread name and the generated random number by the thread
    System.out.println(Thread.currentThread().getName()
        + " generated counter: " + counter);

    for (int i = 0; i < counter; i++) {
      new CallTracker().call();
    }
  }
}

Result

Related Topics