简体   繁体   中英

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!

Would anyone be kind enough to provide a example? Perhaps comparing to the new Java 8 Date classes that are thread safe.

First of all java Date is mutable and hold state -> there is a chance Date to be not a threadsafe.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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