Java ThreadLocal use local thread variables

Introduction

Java Thread-local variables store a field value for each Thread.

We can read the value using the get() method and change the value using the set() method.

The first time when you access the value of a thread-local variable, if it has no value for the Thread object, the thread-local variable calls the initialValue() method to assign a value for that Thread and returns the initial value.

The thread-local class has remove() method that deletes the value stored in the thread-local variable.

No using thread-local variables


import java.util.Date;
import java.util.concurrent.TimeUnit;

class UnsafeTask implements Runnable {
  private Date startDate;

  @Override//from w  ww .  java 2 s  .  c  o  m
  public void run() {
    startDate = new Date();
    System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(), startDate);
    try {
      TimeUnit.SECONDS.sleep((int) Math.rint(Math.random() * 10));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.printf("Thread Finished: %s : %s\n", Thread.currentThread().getId(), startDate);
  }

}

public class Main {
  public static void main(String[] args) {
    // Creates the unsafe task
    UnsafeTask task = new UnsafeTask();

    // Throw three Thread objects
    for (int i = 0; i < 3; i++) {
      Thread thread = new Thread(task);
      thread.start();
      try {
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

Using thread-local variables


import java.util.Date;

import java.util.concurrent.TimeUnit;
public class Main {
  public static void main(String[] args) {
    SafeTask task=new SafeTask();
    // Creates and start three Thread objects for that Task
    for (int i=0; i<3; i++){
      Thread thread=new Thread(task);
      try {//from w  w  w .  j  a  v  a2  s.  com
        TimeUnit.SECONDS.sleep(2);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      thread.start();
    }

  }

}

/**
 * Class that shows the usage of ThreadLocal variables to share
 * data between Thread objects
 *
 */
class SafeTask implements Runnable {
  /**
   * ThreadLocal shared between the Thread objects
   */
  private static ThreadLocal<Date> startDate= new ThreadLocal<Date>() {
    protected Date initialValue(){
      return new Date();
    }
  };
  @Override
  public void run() {
    // Writes the start date
    System.out.printf("Starting Thread: %s : %s\n",Thread.currentThread().getId(),startDate.get());
    try {
      TimeUnit.SECONDS.sleep((int)Math.rint(Math.random()*10));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // Writes the start date
    System.out.printf("Thread Finished: %s : %s\n",Thread.currentThread().getId(),startDate.get());
  }

}



PreviousNext

Related