Make an AtomicXXX object volatile

I have read some info about volatile variables and their AtomicXXX counterparts, (e.g. AtomicBoolean).

But are there situations where I need to make the AtomicXXX object itself volatile, or is it never necessary?

Answer

You don’t need to – in fact, the atomic objects should really be set as final!!

Example:

private final AtomicInteger atomicInt = new AtomicInteger(0);

private volatile int volatileInt = 0;

public void doStuff() {
  // To use the atomic int, you use the setters and getters!
  int gotAnInt = atomicInt.getAndIncrement();

  // To use a volatile, access and set it directly. 
  int gotAnotherInt = volatileInt;
  volatileInt = someOtherInt;
}

Leave a Reply

Your email address will not be published. Required fields are marked *