I need to call ThreadLocal.remove in the following case

Instead of writing the following safe method, different from a stream.

private static final Calendar calendar = Calendar.getInstance(); public void fun() { // Going to call mutable methods in calendar. } 

I am changing it to a safe version.

 public void fun() { final Calendar calendar = Calendar.getInstance(); // Going to call mutable methods in calendar. } 

Instead of creating a new instance every time even for one thread, I made an improvement

 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 third approach, is there a need to call ThreadLocal.remove ?

+4
source share
2 answers

If your only intention is to make it thread safe, then there really is no need to do this. But when threads are supported by threadpool, and your intention is to give each freshly released thread from the thread thread its own initial value, then you should do it.

+5
source

As @BalusC says, it depends on what bothers you.

I have a suspicion that your disposal of Calendar objects using a local stream may actually cost more than you save without calling Calendar.getInstance() . It smells of premature micro optimization.

+2
source

All Articles