开发者

Do I need to call ThreadLocal.remove in the following case

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜