You can't make something thread-safe if it isn't. In the case of Calendar
, even reading data from it isn't thread-safe, as it can update internal data structures.
If at all possible, I'd suggest using Joda Time instead:
- Most of the types are immutable
- The immutable types are thread-safe
- It's a generally much better API anyway
If you absolutely have to use a Calendar
, you could create a locking object and put all the access through a lock. For example:
private static final Calendar calendar = Calendar.getInstance();
private static final Object calendarLock = new Object();
public static int getYear()
{
synchronized(calendarLock)
{
return calendar.get(Calendar.YEAR);
}
}
// Ditto for other methods
It's pretty nasty though. You could have just one synchronized method which created a clone of the original calendar each time it was needed, of course... it's possible that by calling computeFields
or computeTime
you could make subsequent read-operations thread-safe, of course, but personally I'd be loathe to try it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…