I’ve been working under the assumption that neither Date nor Calendar are thread-safe, but, during a recent discussion, a co-worker told me Calendar was thread-safe.
So, I did some research, and came up with nothing. There are plenty people arguing it’s thread-safe, and plenty people arguing it’s not thread-safe. And, to top it off, the documentation doesn’t say anything one way or another, not for Calendar, nor even for Date.
So, which is it?
Here is a link to the source code of Calendar and GregorianCalendar in Java 7
If you read the code you will see that none of the instance methods are synchronized, and none of the instance fields are
volatile. You will also see that even the fieldgetmethods can cause a Calendar instance to mutate. And since there is no synchronization performed, different threads may see stale versions of a Calendar object’s fields following such a mutating operation.For the record, the mutation action in the field get methods happens in / during a call to this method:
In short, the
Calendarclass is not thread-safe, andGregorianCalendarisn’t either because it inherits the non-thread-safe fields and methods.But don’t just take my word for it. Do your own analysis of the source code.
If the javadocs don’t specify the thread-safety of a class, then you should assume that it is not thread-safe. (Especially if the class is mutable by design.)