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?
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?
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:Source: JLS8 section 17.7