简体   繁体   中英

Volatile vs Atomic in Java, why do we need atomic toolkit

Volatile eliminates visibility and ordering issues. While atomic toolkit provides atomicity of operations. Volatile uses happens-before relation and Atomic uses compare and swap.

Why there is a need to introduce new layer of abstraction like atomic toolkit, instead of enhancing volatile keyword itself? Is there any specific cases which may be solved by atomic toolkit?

Actually if you'll take closer look into Atomic* implemetations then you'll see that all of them holds volatile field with value.

IMHO atomics is already an extension of volatile mechanism which provides convenient way to do atomic CAS operations.

Also there is a benefits of hiding CAS implementation. For example hotspot jvm heavily uses intrinsics to achieve to squeeze performance.

Changing an existing language construct like volatile would most likely mean that you break existing applications. So this is typically not an option, in particular not for the Java language. Creating a new library does not effect existing applications and is thus completely backwards compatible.

In addition to that, the classes in the atomic package offer advanced operations like compareAndSet that you cannot just add to the volatile keyword.

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