java - Is simple getter call on volatile variable atomic operation? -
i have following in class:
private static volatile byte counter = 0; public static byte getcounter() {return counter;}
is call getcounter
atomic, or not?
yes, atomic operation, in sense there can no reordering or timing cause byte read while being partially written. if byte reassigned while being read getter guaranteed return either before or after value, no other value, without volatile
.
however, must have volatile
on double or long value avoid getting inconsistent reads neither old nor new value:
for purposes of java programming language memory model, single write non-volatile long or double value treated 2 separate writes: 1 each 32-bit half. can result in situation thread sees first 32 bits of 64-bit value 1 write, , second 32 bits write.
implementations of java virtual machine encouraged avoid splitting 64-bit values possible. programmers encouraged declare shared 64-bit values
volatile
or synchronize programs correctly avoid possible complications.
source: jls8 section 17.7
Comments
Post a Comment