ThreadLocal in Java with Example

ThreadLocal is a class provides way to hold thread local variables and provide access to get and set values. in other words, it allows you to have copy of variables per thread and these variables will be garbage collected when the associated thread dies. ThreadLocal instances are advised to be private static fields in classes. 

For example, in an application that is tightly tied to a database, many methods may need to access the database. It could be inconvenient to include
a Connection as an argument to every method in the system -- a sloppier, but significantly more convenient technique would be to access the connection with a Singleton. However, multiple threads cannot safely share a JDBC Connection. By using a ThreadLocal in our Singleton, as shown in Listing 3, we can allow any class in our program to easily acquire a reference to a per-thread Connection. In this way, we can think of a ThreadLocal as allowing us to create a per-thread-singleton.

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConcurrentDateFormatAccess {

 private ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat> () {

  @Override
  public DateFormat get() {
   return super.get();
  }

  @Override
  protected DateFormat initialValue() {
   return new SimpleDateFormat("yyyy MM dd");
  }

  @Override
  public void remove() {
   super.remove();
  }

  @Override
  public void set(DateFormat value) {
   super.set(value);
  }

 };

 public Date convertStringToDate(String dateString)
     throws ParseException {
  return df.get().parse(dateString);
 }

}


The benefits of ThreadLocal:

ThreadLocal offers a number of benefits. It is often the easiest way to render a stateful class thread-safe, or to encapsulate non-thread-safe classes so that they can safely be used in multithreaded environments. Using ThreadLocal allows us to bypass the complexity of determining when to synchronize in order to achieve thread-safety, and it improves scalability because it doesn't require any synchronization. In addition to simplicity, using ThreadLocal to store a per-thread-singleton or per-thread context information has a valuable documentation perk -- by using a ThreadLocal, it's clear that the object stored in the ThreadLocal is not shared between threads, simplifying the task of determining whether a class is thread-safe or not.

Search:

Recent Posts