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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With