Vaibhav's Blog Space

Atomic Operations in Java

Sunday 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 :-(

[4] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg
Comments:

If your 16-bit CPU support multi processor and incoherence cache, a correct implementation on 16-bit CPU require locking. All of the 16-bit CPU i am aware of use green thread and no extra processor, which need no extra protection.

Posted by Daniel on April 27, 2008 at 09:27 PM IST #

Thats a valid point. Thanks Daniel.

Posted by Vaibhav on April 27, 2008 at 09:33 PM IST #

This is why we have AtomicInteger et. al. No?

Ron

Posted by Ronald Pomeroy on May 14, 2008 at 04:41 AM IST #

Exactly Ron, this is the reason we get AtomicInterger and few more in new concurrency package :)

Posted by Vaibhav Choudhary on May 14, 2008 at 08:31 AM IST #

Post a Comment:
  • HTML Syntax: NOT allowed