How do I create a variable local to a Thread?

John Zukowski

The Java 1.2 release introduced the concept of thread local variables as a standard class. Previously, they existed in the sun.server.util package of the Java WebServer product. Now, you get them in the java.lang.ThreadLocal and java.lang.InheritableThreadLocal classes. These classes permit individual threads to have independent copies of variables. With ThreadLocal, only a particular thread sees the variable, with InheritableThreadLocal a thread and all its descendents can see it.

Here's an example, taken from my Mastering Java 2 book.

public class LocalThreadVars implements Runnable {
  static private class MyThreadLocal extends ThreadLocal {
    protected Object initialValue() {
      return new Double (Math.random() * 1000.0);
  static ThreadLocal threadLocal = new MyThreadLocal();
  static int counter = 0;
  private LocalThreadVars() {
  public void run() {
    LocalThreadVars myLTV = new LocalThreadVars();
    try {
      Thread.currentThread().sleep (
    } catch (InterruptedException e) {
  private void displayValues() {
    System.out.println (threadLocal.get() + "	" + counter + 
      "	" + Thread.currentThread().getName());
  public static void main (String args[]) {
    LocalThreadVars ltv = new LocalThreadVars();
    for (int i=0;i<5;i++) {
      Thread t = new Thread (ltv);