Sunday, 24 April 2016

How to use ThreadLocal ?


1. Context.java  - Bean holding the data : transactionId
public class Context {
  private String transactionId = null;
  /* getters and setters here */
}

2. MyThreadLocal.java - Container to hold our context object
Creating a ThreadLocal object as a static field which can be used by rest of the code to set/get thread local variables.
public class MyThreadLocal {
  public static final ThreadLocal userThreadLocal = new ThreadLocal();
  public static void set(Context user) {
    userThreadLocal.set(user);
  }
  public static void unset() {
    userThreadLocal.remove();
  }
  public static Context get() {
    return userThreadLocal.get();
  }
}

3. BusinessService.java - read from thread local and use the value
public class BusinessService {
  public void businessMethod() {
    // get the context from thread local
   Context context = MyThreadLocal.get();
   System.out.println(context.getTransactionId());
  }
}

4. Main class - generate and set the transaction ID in thread local and then call the business method.
public class ThreadLocalDemo extends Thread {
  public static void main(String args[]) {
    Thread threadOne = new ThreadLocalDemo();
    threadOne.start();

    Thread threadTwo = new ThreadLocalDemo();
    threadTwo.start();
  }

  @Override
  public void run() {
    // sample code to simulate transaction ID
    Context context = new Context();
    context.setTransactionId(getName());

     // set the context object in thread local to access it somewhere else
     MyThreadLocal.set(context);

     // note that we are not explicitly passing the transaction id
     new BusinessService().businessMethod();
     MyThreadLocal.unset();
  }

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.