Tuesday, January 31, 2012

ThreadLocal - Usage and Explanation

Refer to a developer article : http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use

Read documentation on usage first in the above link. Then refer to the following sample code from the developer:


01.package com.veerasundar;
02. 
03.public class Context {
04. 
05.  private String transactionId = null;
06. 
07.        /* getters and setters here */
08. 
09.}
 
01.package com.veerasundar;
02. 
03./**
04. * this class acts as a container to our thread local variables.
05. * @author vsundar
06. *
07. */
08.public class MyThreadLocal {
09. 
10.  public static final ThreadLocal userThreadLocal = new ThreadLocal();
11. 
12.    public static void set(Context user) {
13.      userThreadLocal.set(user);
14.  }
15. 
16.   public static void unset() {
17.        userThreadLocal.remove();
18.   }
19. 
20.   public static Context get() {
21.       return userThreadLocal.get();
22.   }
23.}
 
01.package com.veerasundar;
02. 
03.public class ThreadLocalDemo extends Thread {
04. 
05.   public static void main(String args[]) {
06. 
07.        Thread threadOne = new ThreadLocalDemo();
08.       threadOne.start();
09. 
10.      Thread threadTwo = new ThreadLocalDemo();
11.       threadTwo.start();
12.  }
13. 
14.   @Override
15.   public void run() {
16.     // sample code to simulate transaction id
17.       Context context = new Context();
18.        context.setTransactionId(getName());
19. 
20.        // set the context object in thread local to access it somewhere else
21.       MyThreadLocal.set(context);
22. 
23.     /* note that we are not explicitly passing the transaction id */
24.        new BusinessService().businessMethod();
25.     MyThreadLocal.unset();
26. 
27.  }
28.}
 
01.package com.veerasundar;
02. 
03.public class BusinessService {
04. 
05.  public void businessMethod() {
06.      // get the context from thread local
07.        Context context = MyThreadLocal.get();
08.      System.out.println(context.getTransactionId());
09. }
10.}
 
 

1 comment:

Most frequently ask java interview questions and answers said...

ThreadLocal class allows you to put local data on a thread, so that every module running in the thread can access it. ThreadLocal class in Java- purpose and use with an example