In Java, AtomicInteger
and AtomicLong
seem to implement the same functionality as .NET's Interlocked
. Additionally, they provide a get()
method to read the most current value (which may differ from that stored in the CPU cache):
private volatile int value;
// ...
/**
* Gets the current value.
*
* @return the current value
*/
public final int get() {
return value;
}
On the other hand, Interlocked
only provides a Read(...)
method for 64-bit values, which only guarantees they're read consistently (i.e. on 32-bit system you don't read any garbage), but not that the value read is the most current one.
Now the question. If I use a volatile
variable in conjunction with Interlocked
, does it guarantee that the value can be both incremented/decremented and read/written atomically?