Atomic Operations in Java
By vaibhavc on Apr 27, 2008
Knowing atomic operation is very important when we are writing thread operation in Java. Covering atomic operation inside synchronized keyword is just a overhead which we discussed sometime back in one post. Now what all comes under atomic operation:
1. a = a + 1 - certainly not. Because this operation can use a local variable or a register to store the information before assigning it back to a. This operation is more or less like:
temp = a+1;
a = temp;
2. a = b; Is this a atomic operation ? It depends ! Java Specification says that assignment to variables smaller than or equal to 32 bits is an atomic operation, which excludes variables of types double and long (both are 64 bits). So, the operation is atomic or not completely depends on type of a and b. Now, reason behind such a specification is very clear, any operation more than 32 bit should need a extra storage(basically register) for a 32 bit processor. But here Java Spec is not speaking about any processor dependency. Now, I am surprised how VM will handle atomicity if ran on 16 bit processor. I don't know but I guess we can run JVM on 16 bit processor. Is it handles atomicity internally ? How about 64 bit processor. Even double and long operation should be atomic.
I am confused :-(