Atomic Operations in Java

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

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 02:27 PM IST #

Thats a valid point. Thanks Daniel.

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

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

Ron

Posted by Ronald Pomeroy on May 13, 2008 at 09:41 PM 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 01:31 AM IST #

thank you very very hell.thank you very very hell.

Posted by webmaster forumu on November 23, 2009 at 11:02 AM IST #

Hi Vaibhav,

So which operation's are exactly atomic in Java ? I see only assignment to 32 bit variable as atomic here .

Thanks
Javin

Posted by Javin Paul on January 04, 2011 at 11:32 AM IST #

Post a Comment:
Comments are closed for this entry.
About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today