Been trying to find the best way to implement a method that makes a defensive copy of a Calendar object.
eg:
public void setDate(Calendar date) {
Just wrap your Calendar object into ThreadLocal. This will guarantee that each instance of Calendar is used only by one thread. Something like this:
public class ThreadLocalCalendar
{
private final static ThreadLocal CALENDAR =
new ThreadLocal ()
{
@Override
protected Calendar initialValue()
{
GregorianCalendar calendar = new GregorianCalendar();
// Configure calendar here. Set time zone etc.
return calendar;
}
};
// Called from multiple threads in parallel
public void foo ()
{
Calendar calendar = CALENDAR.get ();
calendar.setTime (new Date ());
// Use calendar here safely, because it belongs to current thread
}
}