2

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?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Kumar
  • 1,536
  • 2
  • 23
  • 33
  • 1
    You probably should make it `final`, instead of `volatile`. If `final` doesn't work for you, then you are either doing something very tricky, or else you may be making a mistake. Don't forget that the variable `a` is _not_ an `AtomicInteger`. The `a` variable holds a _reference_ to a mutable `AtomicInteger` heap object. In the normal way of using `AtomicInteger`, the different parts of your program and its different threads would all communicate by mutating and inspecting the same shared object, and _not_ by changing which object the `a` variable refers to. – Solomon Slow Aug 08 '20 at 18:05

2 Answers2

2

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

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.

pveentjer
  • 10,545
  • 3
  • 23
  • 40