是java.util.Calendar线程安全还是不? [英] Is java.util.Calendar thread safe or not?

查看:3716
本文介绍了是java.util.Calendar线程安全还是不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在假设 Date Calendar 都是线程安全的,但在最近一次讨论,一个同事告诉我日历是线程安全的。



,并没有想出任何东西。有很多人认为它是线程安全的,有很多人认为它不是线程安全的。而且,为了优先,文档不会以任何方式说,不是日历,甚至日期

解决方案

$ p

以下是日历的源代码的链接, Java 7中的GregorianCalendar



如果你读取代码,你会看到没有一个实例方法被同步,并且没有一个实例字段是 volatile 。您还将看到,即使字段 get 方法也可能导致日历实例发生变异。并且由于没有执行同步,不同的线程可能在这样的变异操作之后看到日历对象的字段的陈旧版本。



对于记录,字段get方法中的变异操作发生在调用此方法时/中:

  1555 protected void complete()
1556 {
1557 if(!isTimeSet)
1558 updateTime
1559 if(!areFieldsSet ||!areAllFieldsSet){
1560 computeFields(); //填充未设置的字段
1561 areAllFieldsSet = areFieldsSet = true;
1562}
1563}

总之, Calendar 类不是线程安全的, GregorianCalendar 不是因为它继承了非线程安全的字段和方法。 p>

但不要只是接受我的话。自己分析源代码。








如果javadoc不指定一个类的线程安全性,那么你应该假定它不是线程安全的。


I've been working under the assumption that neither Date nor Calendar are thread-safe, but, during a recent discussion, a co-worker told me Calendar was thread-safe.

So, I did some research, and came up with nothing. There are plenty people arguing it's thread-safe, and plenty people arguing it's not thread-safe. And, to top it off, the documentation doesn't say anything one way or another, not for Calendar, nor even for Date.

So, which is it?

解决方案

Here is a link to the source code of Calendar and GregorianCalendar in Java 7

If you read the code you will see that none of the instance methods are synchronized, and none of the instance fields are volatile. You will also see that even the field get methods can cause a Calendar instance to mutate. And since there is no synchronization performed, different threads may see stale versions of a Calendar object's fields following such a mutating operation.

For the record, the mutation action in the field get methods happens in / during a call to this method:

 1555 protected void complete()
 1556       {
 1557           if (!isTimeSet)
 1558               updateTime();
 1559           if (!areFieldsSet || !areAllFieldsSet) {
 1560               computeFields(); // fills in unset fields
 1561               areAllFieldsSet = areFieldsSet = true;
 1562           }
 1563       }

In short, the Calendar class is not thread-safe, and GregorianCalendar isn't either because it inherits the non-thread-safe fields and methods.

But don't just take my word for it. Do your own analysis of the source code.


And, to top it off, the documentation doesn't say anything one way or another, not for Calendar, nor even for Date.

If the javadocs don't specify the thread-safety of a class, then you should assume that it is not thread-safe.

这篇关于是java.util.Calendar线程安全还是不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆