Java knowledge about Atomic Operation of Increment Operator

An atomic operation is an operation which is performed as a single unit of work without the possibility of interference from other operations.

A Java question and knowledge transfer about Atomic Operation.

Refer to the following code:


public void someMethod() {
int a = 1;
a++;
}

Normally the final result of variable a is 2, but the value can be other possible such as 3 or 4. Why?

It is because in Java the language specification guarantees that that reading or writing a variable is atomic (unless the variable is of type long or double). Long and double are only atomic if they declared as volatile.

The operation a++ it not atomic in Java for the standard variables (int, long, etc). It first reads the value which is currently stored in a (atomic operations) and then it adds one to it (atomic operation). But between the read and the write the value of a might have changed.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply