Is simple getter call on volatile variable atomic operation?

218 views Asked by At

I have the following in my class:

private static volatile byte counter = 0;
public static byte getCounter() {return counter;}

Is the call to getCounter atomic, or not?

1

There are 1 answers

0
nanofarad On BEST ANSWER

Yes, it is an atomic operation, in the sense that there can be no reordering or timing that will cause the byte to be read while being partially written. If the byte is reassigned while it is being read the getter is guaranteed to return either the before or the after value, but no other value, even without volatile.

However, you must have volatile on a double or long value to avoid getting inconsistent reads that are neither the old nor the new value:

For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.

Implementations of the Java Virtual Machine are encouraged to avoid splitting 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid possible complications.

Source: JLS8 section 17.7