Thread-Local means local to thread.In Context of java ,Thread-local means "every thread that will access thread-local variable will have its own instantiated copy of variable ".
See the below example:
If you look the output of above program than you will find that when different thread calls getDateFormatter() method of SimpleDateFormatPerThread class than its call its initialValue() method which creates exclusive instance of SimpleDateFormat for that Thread. Since SimpleDateFormat is not shared between thread and essentially local to the thread which creates its our threadSafFormat() method is completely thread-safe.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThreadLocalTest
{
public static void main(String[] args)
{
Thread t1 = new Thread(new ThreadTask());
Thread t2 = new Thread(new ThreadTask());
t1.start();
t2.start();
}
}
class SimpleDateFormatPerThread
{
private static final ThreadLocal<SimpleDateFormat> dateFormatHolder = new ThreadLocal<SimpleDateFormat>() {
/*
* initialValue() is called
*/
@Override
protected SimpleDateFormat initialValue() {
System.out.println("Creating SimpleDateFormat for Thread : " + Thread.currentThread().getName());
return new SimpleDateFormat("dd/MM/yyyy");
}
};
/*
* Every time there is a call for DateFormat, ThreadLocal will return calling
* Thread's copy of SimpleDateFormat
*/
public static DateFormat getDateFormatter() {
return dateFormatHolder.get();
}
/*
* Thread safe format method because every thread will use its own DateFormat
*/
public static String threadSafeFormat(Date date){
DateFormat formatter = SimpleDateFormatPerThread.getDateFormatter();
return formatter.format(date);
}
}
class ThreadTask implements Runnable
{
@Override
public void run()
{
for (int i = 0; i < 2; i++) {
System.out.println("Thread name"+Thread.currentThread().getName()+" "+SimpleDateFormatPerThread.threadSafeFormat(new Date()).toString());
}
}
}
Output:
/*
Creating SimpleDateFormat for Thread : Thread-1
Creating SimpleDateFormat for Thread : Thread-0
Thread nameThread-0 16/01/2013
Thread nameThread-0 16/01/2013
Thread nameThread-1 16/01/2013
Thread nameThread-1 16/01/2013
/*
To get more clarity about thread safety issue with SimpleDateFormat class ,just go through below link:
http://www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html
No comments:
Post a Comment