而不是编写以下非线程安全的方法。
private static final Calendar calendar = Calendar.getInstance();
public void fun() {
// Going to call mutable methods in calendar.
}
我将其更改为线程安全版本。
public void fun() {
final Calendar calendar = Calendar.getInstance();
// Going to call mutable methods in calendar.
}
即使对于同一个线程,我也没有每次都创建一个新实例,而是通过以下方式进行了改进
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();
}
};
对于我的第三种方法,是否需要调用ThreadLocal.remove
?