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

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -