Today during a telephonic interview, my interviewer asked me what is the default atomicity of a java statement.
She explained further that she wants to know if we can be sure that a certain instruction will always be atomic even if we have it in a non synchronized context in a multi-threaded environment.
I said we couldn't be sure. The scheduler probably does not check the stage of execution of a thread before putting it back to runnable. But I am not sure if it was the right answer. I have been thinking about it for a while. Should a single instruction at byte code level be atomic by default? One statement could mean many byte code instructions. So would a single byte code instruction be atomic?
A single read or write to a variable that's not a double or long is atomic. So if there are two threads where one thread modifies an int and another reads it, the second thread reads either the old value or the new one, and not some corrupted value. A statement that does multiple reads or writes like "x++" is not guaranteed to be atomic.
Chan Ag wrote:Why not for double and long variables?
Because they aren't stored in one register in memory. Which means on the assembly language level there are two instructions. HOwever, I don't think that level is what is meant by automicity. Usually we talk about atomic as meaning the illusion of atomic. In that no other Java commands get run in between.
The JVM spec (section 17.7) has more info on this.
Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32 bit values. For efficiency's sake, this behavior is implementation specific; Java virtual machines are free to perform writes to long and double values atomically or in two parts.
For the purposes of the Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64 bit value from one write, and the second 32 bits from another write. Writes and reads of volatile long and double values are always atomic. Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.
VM implementors are encouraged to avoid splitting their 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid possible complications.
So the answer is 'it depends'. A JVM implementation might as well write the 64 bit value atomically. A guarantee is made on the atomicity of the read / write if the variable is volatile. Or you could use a synchronized block to ensure other threads read an updated value and writes are performed in program order.