"how to make a static calendar thread safe" Code Answer


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()
        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.

By axel.michel on January 15 2022

Answers related to “how to make a static calendar thread safe”

Only authorized users can answer the Search term. Please sign in first, or register a free account.