Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is simple getter call on volatile variable atomic operation?

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?

like image 273
artaxerxe Avatar asked Jun 19 '15 11:06

artaxerxe


Video Answer


1 Answers

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

like image 172
nanofarad Avatar answered Oct 04 '22 19:10

nanofarad