10

I'd like to use a Calendar for some static methods and use a static field:

private static Calendar calendar = Calendar.getInstance();

Now I read java.util.Calendar isn't thread safe. How can I make this thread safe (it should be static)?

6
  • Is your static calendar just a fixed date?
    – toto2
    Commented Jun 5, 2011 at 18:57
  • maybe it would help to make it "volatile" ?
    – cody
    Commented Jun 5, 2011 at 18:57
  • no, I just don't want to create so many instances - for every call to my methods, as that possibly could take time.
    – cody
    Commented Jun 5, 2011 at 18:59
  • You mean you are worried about the performance hit of many calls to the constructor?
    – toto2
    Commented Jun 5, 2011 at 19:00
  • 2
    I am beginning to conclude that Calendar should not be regarded as simply "not thread safe." It should be labeled "thread hostile".
    – scottb
    Commented Jun 6, 2013 at 17:35

6 Answers 6

14

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.

32
  • If you clone a template, you dont need synchronized block.As the template itself is immutable.
    – bestsss
    Commented Jun 5, 2011 at 19:01
  • Even though a read on Calendar updates internal state, can you give an example of when two threads might try to set different values for that state? Commented Jun 5, 2011 at 19:01
  • @bestsss: Well, that depends on whether clone itself is thread-safe. Given the lack of thread safety in the rest of Calendar, I wouldn't want to rely on it.
    – Jon Skeet
    Commented Jun 5, 2011 at 19:03
  • 1
    @Peter: Imagine if areFieldsSet becomes visible as true to one thread due to the computation in another before the computed field values themselves become visible. It would potentially be possible for one thread to read some old field values and some new ones, leading to weird results. I don't like trying to reason about implementation details to decide whether or not that's possible.
    – Jon Skeet
    Commented Jun 5, 2011 at 19:05
  • 1
    @Voo: My alarm clock could be set to wake me up at 8 o'clock local time every day, wherever I am. What time zone should that use in its representation? ;)
    – Jon Skeet
    Commented Jun 5, 2011 at 19:36
3

Calendar is thread safe provided you don't change it. The usage in your example is fine.

It is worth noting that Calendar is not an efficient class and you should only use it for complex operations (like finding the next month/year) IMHO: If you do use it for complex operations, use local variables only.

If all you want it a snapshot of the time a faster way is to use currentTimeMillis which does even create an object. You can make the field volatile if you want to make it thread safe.

private static long now = System.currentTimeMillis();

The usage is a bit suspect. Why would you get the current time and store it globally like this. It reminds me of the old joke.

- Do you have the time?
- Yes, I have it written down somewhere.

6
  • 2
    What exactly do you mean by "change it" bearing in mind that reading from it can change its internal state? I wouldn't be entirely surprised to find that two simultaneous read operations could potentially end up corrupting state. It's unlikely, but I wouldn't like to rely on it. Calendar is a nasty, nasty class :(
    – Jon Skeet
    Commented Jun 5, 2011 at 19:03
  • Reading it won't change its state in inconsistent ways. If you were worried about this you would have to say the same thing about String.hashCode(). Commented Jun 5, 2011 at 19:04
  • I agree that Calendar is nasty. Have you tried Serializing it? It sends the entire TimeZone information which is not great for performance but it means if you have a system which has up to date TimeZone information, but you read an old Calendar or get a Calendar from a system which is not up to date you get subtle TimeZone issues you never expected to happen due to bugs in code you are not running. :P Commented Jun 5, 2011 at 19:07
  • 4
    See my comment replying to you in my answer. String is designed to be thread-safe, so its hash caching is thread-safe: the value is atomically changed from "uncached" to "the cached value". Compare that with Calendar, where a boolean field determines whether the fields are set, and the fields themselves are separate. What guarantees that all changes to that set of data occurs atomically, or in a desirable order?
    – Jon Skeet
    Commented Jun 5, 2011 at 19:08
  • 1
    @scottb Part of what makes Calendar slow is creating the TimeZone and Locale objects. If you cache these immutable objects, you can make creating new Calendar faster. To make Calendar thread safe you need to lock it while using it. Commented Jun 7, 2013 at 5:39
3

tl;dr

Calendar replaced by ZonedDateTime. Immutable, so thread-safe.

private static ZonedDateTime someMoment = ZonedDateTime.now();  // Capture the current moment as seen in the JVM’s current default time zone.

If the value is meant to be fixed, unchanging during the execution of your app, mark it final.

private static final ZonedDateTime someMoment = ZonedDateTime.now();  

If at runtime you might assign a different object, then for thread-safety use an AtomicReference.

private static final AtomicReference< ZonedDateTime > someMomentRef = new AtomicReference<>( ZonedDateTime.now() ) ;

Later updating with a fresh moment.

someMomentRef.set( ZonedDateTime.now() );

If you need to interoperate with old code not yet updated to java.time, convert.

ZonedDateTime someMoment = someMomentRef.get() ;
Calendar c = GregorianCalendar.from( someMoment ) ;  // `GregorianCalendar` is a concrete subclass of `Calendar`.

java.time.ZonedDateTime

The terribly flawed java.util.Calendar class has been supplanted by the modern java.time classes defined in JSR 310. Specifically replaced by java.time.ZonedDateTime.

A ZonedDateTime object represents a date with time-of-day as seen in a particular time zone.

Understand that a time zone is a named history of the changes to the offset used by the people of a particular region as decided by their politicians. An offset is merely a number of hours-minutes-seconds ahead or behind the temporal meridian of UTC.

To get the current moment, specify your desired/expected time zone.

ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

If you want the JVM’s current default time zone, use ZoneId.systemDefault().

You can store a ZonedDateTime object in a static reference. But be aware that such an object stores a frozen moment, is immutable, and does not adjust to later moments. If you want a later moment, call now method ago to generate a new fresh ZonedDateTime object.

private static final ZonedDateTime appLaunched = ZonedDateTime.now( ZoneId.of( "Asia/Tokyo" ) );

java.time.Instant

If you merely want to track a moment, a specific point on the timeline, without business rules explicitly aimed at time zones, use a moment as seen in UTC. For that, use java.time.Instant class.

private static final Instant instant = Instant.now() ;  // Always in UTC, an offset of zero.

Generating localized text

You can later apply a time zone for presentation to the user.

ZonedDateTime zdt = instant.atZone( ZoneId.systemDefault() ) ;
String output = 
    zdt
    .atZone( ZoneId.systemDefault() )  // Returns a `ZonedDateTime` object.
    .format( 
        DateTimeFormatter
        .ofLocalizedDateTime( FormatStyle.FULL )  // Returns a `DateTimeFormatter` object.
        .withLocale( Locale.getDefault() )
    ) ;  // Returns a `String` object.
2

You cannot. Yes, you could synchronize on it, but it still has mutable state fields. You'll have to create your own Calendar object.

If possible, use something lightweight, like a long measuring the times in milliseconds, and only convert to a Calendar when you NEED to.

2

Instead of trying to make the Calendar API thread-safe, use the thread-safe java.time API introduced in Java 8 instead. This API also provides a more fluent and intuitive interface for date and time manipulation.

Here's an example compatible with the legacy Date API of getting the start of next day with the java.time API:

import java.time.LocalDateTime;
import java.time.ZoneId;

public static Date getStartOfNextDay() {
    final ZonedDateTime startOfNextDay = ZonedDateTime.now()
            .plusDays(1)
            .withHour(0).withMinute(0).withSecond(0).withNano(0);
    return Date.from(startOfNextDay.toInstant());
}

And here's how it looks with the Calendar API:

import java.util.Calendar;

public static Date getStartOfNextDay() {
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}
4
  • 2
    I do not see how using LocalDateTime in this code adds value. The replacement for java.util.Calendar is java.time.ZonedDateTime. Commented Jul 21, 2023 at 21:03
  • @BasilBourque, on a second glance, my answer is a unintentional copy of your answer. What do you think, should I remove mine in favor of yours?
    – mrts
    Commented Jul 25, 2023 at 19:48
  • 1
    Leave it. You've gotten an up-vote. An alternate example does not hurt. And your Answer inspired mine. I do suggest you add a bit of explanation of the code. Commented Jul 25, 2023 at 19:59
  • Thank you for the suggestion! The API in the code snippet looks quite readable and fluent, and the code appears to be self-explanatory - don't you think so?
    – mrts
    Commented Jul 28, 2023 at 15:53
-1

Create a Calendar as a local variable in the method. If you need the same calendar across methods, you may be using statics where a (singleton or quasi-singleton) object would be more appropriate.

1
  • 4
    Are you really suggesting that making a singleton of a mutable, non-thread safe object will help make its class thread safe? Really?
    – scottb
    Commented Jun 6, 2013 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.