简体   繁体   English

证明旧的Date Java API不是线程安全的

[英]Proof that old Date Java API is not thread safe

I've been looking for code that demonstrates the kind of stuff that could happen when you use the legacy Date or Calendar classes in a multi-threaded environment, but I can't seem to find any good examples, found a couple with the DateFormatter but nothing only with either of the mentioned two classes anywhere, it is always mentioned they're not thread safe but no code examples! 我一直在寻找能够演示在多线程环境中使用遗留日期或日历类时可能发生的事情的代码,但我似乎找不到任何好的例子,发现了一对使用DateFormatter但是没有任何地方只提到任何一个提到的两个类,它总是被提到它们不是线程安全但没有代码示例!

Would anyone be kind enough to provide a example? 有人会善意提供一个例子吗? Perhaps comparing to the new Java 8 Date classes that are thread safe. 也许比较线程安全的新Java 8 Date类。

First of all java Date is mutable and hold state -> there is a chance Date to be not a threadsafe. 首先,java Date是可变的并且保持状态 - >有一个机会Date不是线程安全的。

Since java Date contains state ( transient long fastTime) and getter and setter for this field there is a chance Date to be not thread safe. 由于java Date包含状态(transient long fastTime)以及此字段的getter和setter,因此Date有可能不是线程安全的。

But when setting and getting a long value is not an atomic operation? 但是设置和获取长值不是原子操作吗? If you are running the code in 32bit operation system setting long to a primitive field is not atomic operation, because long and double values were treated as two 32-bit values and that is the reason. 如果您在32位操作系统中运行代码设置长到原始字段不是原子操作,因为long和double值被视为两个32位值,这就是原因。

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

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