Reputation: 141
I've just read a question here, and read the most rated answer by @JB Nizet, and I got confused... According to the answer, in the following code,
private int a=0;
public void foo(){
int temp=35;
a=28;
a=temp;
}
a=28;
is an atomic operation.
In some other questions and answers that I've read in Stackoverflow, the information was different, saying that a=28;
is not an atomic operation, because first a read operation of the right operand should take place, then the write operation takes place, and each of these 2 operations is atomic, but the entire assignment is not (To be honest, this is how I thought it works).
And what about a=temp;
? Is it any different than a=28;
in terms of atomicity?
By the way, I know about the need of volatile for double and long to make read/write to them atomic, just confused about what I wrote above.
Can someone plz elaborate on this?
Thanks..
Upvotes: 1
Views: 199
Reputation: 30335
According to the official documentation:
Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
Since a=28;
is a write into a primitive which isn't long or double, it's atomic.
However a=temp
isn't atomic since it consists of two separate operations - the read from temp
and the write to int
. Each of these is atomic, but not their composition.
Upvotes: 6