Is a simple getter call an active variable atomic operation?

My class has the following:

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

Is the getCounter call atomic or not?

+6
source share
1 answer

Yes, this is an atomic operation, in the sense that there can be no reordering or time that will lead to the reading of a byte during partial writing. If the byte is reassigned while it is being read, it is guaranteed that the recipient will be returned a value before or after, but no other value even without volatile .

However, you must have volatile in double or long value to avoid getting incompatible reads that are neither old nor new:

For the purposes of the Java programming language memory model, one record in a non-volatile long or double value is considered as two separate records: one for each 32-bit half. This can lead to a situation where the stream sees the first 32 bits of a 64-bit value from one record and the second 32 bits from another record.

Implementations of the Java virtual machine are recommended to avoid splitting 64-bit values ​​where possible. Programmers are advised to declare common 64-bit values ​​as volatile or to synchronize their programs correctly in order to avoid possible complications.

Source: JLS8 Section 17.7

+10
source

Source: https://habr.com/ru/post/989397/


All Articles