Kumar
Kumar

Reputation: 1666

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?

Upvotes: 2

Views: 120

Answers (2)

pveentjer
pveentjer

Reputation: 11307

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.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198024

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.

Upvotes: 2

Related Questions