简体   繁体   中英

Volatile keyword on Atomic Variable

The following code is valid in Java

volatile AtomicInteger a = new AtomicInteger(123);

Do we require volatile keyword on Atomic variables such as AtomicInteger ? Or is volatile superfluous?

It's superfluous for most sane use cases, but conceivably applicable to some weird cases -- not that I can think of any. When in doubt, use final .

volatile is superfluous because the variable inside the AtomicInteger already is volatile and will provide the happens-before relation that is required. Just make the field final.

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