简体   繁体   English

Calendar.getInstance线程安全

[英]Calendar.getInstance thread safety

If I have a following method; 如果我有以下方法; is a call to Calendar.getInstance() thread-safe? 是对Calendar.getInstance()线程安全的调用吗?

 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. 我的理解是Calendar.getInstance()不是线程安全的,所以下面的方法不能是线程安全的。 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. 我知道Joda-Time被提升为日期时间API的最佳实践,但在这里我坚持使用标准的java.util.Date/Calendar类。

Yes, Calendar.getInstance() is thread-safe because each call creates and returns a new instance. 是的, Calendar.getInstance()是线程安全的,因为每次调用都会创建并返回一个新实例。 You're not gaining anything by synchronizing or by storing the value returned by getTime() in a temporary variable. 通过同步或将getTime()返回的值存储在临时变量中,您无法获得任何东西。

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. 不需要在我看来同步它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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