calendar java 线程安全,是java.util.Calendar线程安全还是不?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值