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?
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?
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;
}
Read this for some tips and explanation when to use volatile. But basically if you are using AtomicXXX you DO NOT NEED to use volatile.