Do I need to call ThreadLocal.remove in the following case
-
30-09-2019 - |
Question
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
?
Solution
If your only intent is to make it threadsafe, then there is indeed no need to do so. But when the threads are maintained by a threadpool and your intent is more to give each freshly released thread from a threadpool its own initial value, then you should do so.
OTHER TIPS
As @BalusC says, it depends on what you are concerned about.
I have a suspicion that your recycling of Calendar
objects using a thread local may actually be costing more than you are saving by not calling Calendar.getInstance()
. This has the smell of a premature micro-optimization.