views:

120

answers:

2

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?

+3  A: 

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.

BalusC
+2  A: 

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.

Stephen C
But, Joshua Bloch even suggest using ThreadLocal for SimpleDateFormat example. (I plan to use for Calendar, SimpleDateFormat and NumberFormat) - http://old.nabble.com/Threadlocals-and-memory-leaks-in-J2EE-td13097957.html#a13097957
Yan Cheng CHEOK
But nothing! Rule #1 of optimization - profile you application first.
Stephen C
@Yan Cheng `Calendar` should be a quite cheap object to construct.
Tom Hawtin - tackline