Saturday, February 27, 2010

ThreadLocal Example in Java

To share a some object associated or linked with 1 thread at any point of time and do not want to modify this value by any other thread then ThreadLoal is useful.This also avoids no need to think about synchrniation,because each thread maintain's it's own copy.

public class ThreadLocalExample extends Thread {

private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};

public static int get() {
return ((Integer) (serialNum.get())).intValue();
}

public void run() {
for(int i=1;i<30;i++)
    System.out.println("Name : " + Thread.currentThread().getName() +" Value : " + get());
  }

  public static void main(String[] args) {
    Thread t1 = new ThreadLocalExample();
    Thread t2 = new ThreadLocalExample();
    Thread t3=new ThreadLocalExample();
    t1.start();
    t2.start();
    t3.start();
  }
}

For more information on ThreadLocal class usage http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

To understand this concept more clearly execute the above program and observe the output.

1 comment:

  1. here is another example of ThreadLocal in Java, which makes SimpleDateFormat thread safe, worth looking.

    ReplyDelete