Search code examples
javavolatile

can java atomic integer be implemented without declaring value volatile?


It occurs to me CAS alone could insure the atomicity of atomic integers. so why bother declare the underlying value volatile?

I know volatile prevents compiler and hardware reordering, and ensures the instruction order. But is that relevant here ?

What's the problem here? What is the problem without volatile?


Solution

  • Assuming it's the Atomic* classes from java.util.concurrent.atomic package.

    You are talking about two different concepts: the reference to the atomic object and the atomic object itself.

    True, CAS on the same atomic integer object is atomic. But how can we be sure that the compareAndSet method calls in two threads are applied to the same object? Just like any java object that are shared by multiple threads, this is related to the safe-publication of the [atomic] object.

    This is where volatile, final member variables or locking comes in useful. The reference to the object should be properly shared by multiple threads.

    After rereading the question, I see you could be asking why the value member in AtomicInteger is declared volatile. For starters, not all methods are based on unsafe.compareAndSwapInt, there are simple set and get that directly access the value field, this is enough reason for this field to be volatile. I wonder it's also required for the unsafe operations.