简体   繁体   中英

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.

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.

Why do you mean by thread safe in this context? you are not modifying any variable and the time is managed by the system. So any call to that method will give you a the current time of your system. No need to synchonise it on my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM