Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calendar.getInstance thread safety

If I have a following method; is a call to Calendar.getInstance() thread-safe?

 public Date currentTime() {
    Date d = null;
    synchronized(this){
        d = Calendar.getInstance().getTime();
    }
    return d;
 }

My understanding is Calendar.getInstance() isn't thread safe so following method can't be thread safe. Is it correct?

public Date currentTime() {
    return Calendar.getInstance().getTime();

}

I understand Joda-Time is promoted as a best practice for date-time APIs but here I am stuck with standard java.util.Date/Calendar classes.

like image 787
user2066049 Avatar asked Dec 26 '22 13:12

user2066049


1 Answers

Yes, Calendar.getInstance() is thread-safe because each call creates and returns a new instance. You're not gaining anything by synchronizing or by storing the value returned by getTime() in a temporary variable.

like image 76
Sotirios Delimanolis Avatar answered Jan 07 '23 22:01

Sotirios Delimanolis