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)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
If you absolutely have to use a
Calendar, you could create a locking object and put all the access through a lock. For example: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
computeFieldsorcomputeTimeyou could make subsequent read-operations thread-safe, of course, but personally I’d be loathe to try it.