Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile declaration on int primitive type

I am quoting from Oracle's Java documentation on Atomic Access

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

I understand how volatile works. But mentioning the requirement to declare volatile explicitly for long and double variables to get atomic access in the second statement, is making volatile declaration for reference variables and for most primitive variables (all types except long and double) in the first statement optional.

But I am seeing codes which use explicit volatile declaration in int primitive type to achieve atomic access; and not doing so not guaranteeing atomic access.

int variable1;          // no atomic access
volatile int variable2; // atomic access

Am I missing something?

like image 989
Alanpatchi Avatar asked May 16 '18 15:05

Alanpatchi


Video Answer


1 Answers

The first statement does not refer to making reference variables and primitive variables (except long and double) volatile.

It says reads and writes of all reference variables and all primitives except long and double are atomic (by default). To make reads and writes of long and double atomic they need to be volatile.

Atomicity does not have anything to do with visibility.

The following paragraph on the same doc

Atomic actions cannot be interleaved, so they can be used without fear of thread interference. However, this does not eliminate all need to synchronize atomic actions, because memory consistency errors are still possible. Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.

So, statements like a = 1 where a is an int (for example) are atomic but you still need to have volatile if you want the assignment to be visible for any subsequent reading threads.

Reading/Writing to a long/double variable is a compound action and making it volatile ensures that it is atomic.

like image 152
user7 Avatar answered Sep 25 '22 09:09

user7