I know volatile allows for visibility, AtomicInteger allows for atomicity.
So if I use a volatile AtomicInteger, does it mean I don’t have to use any more synchronization mechanisms?
Eg.
class A {
private volatile AtomicInteger count;
void someMethod(){
// do something
if(count.get() < 10) {
count.incrementAndGet();
}
}
Is this threadsafe?
I believe that
Atomic*actually gives both atomicity and volatility. So when you call (say)AtomicInteger.get(), you’re guaranteed to get the latest value. This is documented in thejava.util.concurrent.atomicpackage documentation:Now if you have
the
volatilepart means that each thread will use the latestAtomicIntegerreference, and the fact that it’s anAtomicIntegermeans that you’ll also see the latest value for that object.It’s not common (IME) to need this – because normally you wouldn’t reassign
countto refer to a different object. Instead, you’d have:At that point, the fact that it’s a
finalvariable means that all threads will be dealing with the same object – and the fact that it’s anAtomic*object means they’ll see the latest value within that object.