[ACCEPTED]-Is java.util.Calendar thread safe or not?-calendar

Accepted answer
Score: 37

Here is a link to the source code of Calendar and 20 GregorianCalendar in Java 7

If you read the code you will 19 see that none of the instance methods are 18 synchronized, and none of the instance fields 17 are volatile. You will also see that even the field 16 get methods can cause a Calendar instance to 15 mutate. And since there is no synchronization 14 performed, different threads may see stale 13 versions of a Calendar object's fields following 12 such a mutating operation.

For the record, the 11 mutation action in the field get methods 10 happens in / during a call to this method:

 1555 protected void complete()
 1556       {
 1557           if (!isTimeSet)
 1558               updateTime();
 1559           if (!areFieldsSet || !areAllFieldsSet) {
 1560               computeFields(); // fills in unset fields
 1561               areAllFieldsSet = areFieldsSet = true;
 1562           }
 1563       }

In 9 short, the Calendar class is not thread-safe, and 8 GregorianCalendar isn't either because it inherits the non-thread-safe 7 fields and methods.

But don't just take my 6 word for it. Do your own analysis of the 5 source code.


And, to top it off, the documentation 4 doesn't say anything one way or another, not 3 for Calendar, nor even for Date.

If the javadocs 2 don't specify the thread-safety of a class, then 1 you should assume that it is not thread-safe.

Score: 4

Documentation from Oracle says nothing about 4 thread-safety: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html.

OpenJDK source code (build 3 b147) implements java.util.Calendar in a non-thread-safe way, for 2 example:

public void setTimeInMillis(long millis) {
  // skipped
  time = millis;
  isTimeSet = true;
  areFieldsSet = false;
  computeFields();
  areAllFieldsSet = areFieldsSet = true;
}

I think that it's safe to assume 1 that the class is not thread safe.

More Related questions