Instead of writing the following non-thread safe method.
private static final Calendar calendar = Calendar.getInstance();
public void fun() {
// Going to call mutable methods in calendar.
}
I change it to a thread safe version.
public void fun() {
final Calendar calendar = Calendar.getInstance();
// Going to call mutable methods in calendar.
}
Instead of creating a new instance each time even for a same thread, I did the improvement by
public void fun() {
final Calendar calendar = getCalendar();
// Going to call mutable methods in calendar.
}
/**
* Returns thread safe calendar.
* @return thread safe calendar
*/
public Calendar getCalendar() {
return calendar.get();
}
private static final ThreadLocal <Calendar> calendar = new ThreadLocal <Calendar>() {
@Override protected Calendar initialValue() {
return Calendar.getInstance();
}
};
For my 3rd approach, is there any need to call the ThreadLocal.remove
?