Wednesday, June 1, 2011

Myth : Volatile means atomic!!

Volatile means visibility but sometimes people confuse it with atomicity.
Consider the following code:
volatile int i = 0;

//Thread 1:
i++;

//Thread 2:
i--;


So is the above code thread-safe?
The answer to this lies on 2 things -
  • i++ and i-- 
    are not atomic operations. See here for atomic operations. Read the integer to local, increment local and write back integer to the volatile field i.
  • volatile only guarantees visibility between the threads
So above code can be read as :
//Thread 1:r1,r2 local values
r1 = i;
r2 = r1 + 1;
i = r2;

//Thread 2:
r3 = i;
r4 = r3 - 1;
i = r4;
So, if Threads 1 and 2 both read v and see the value 0, then Thread 1 will write 1 to it and Thread 2 will write -1 to it. You are not guaranteed to see the value 0!
So to make above code thread-safe, you should use java.util.concurrent.atomic classes, which allows to create object and allow atomic increment and decrement with support from hardware or processor level.

No comments:

Post a Comment

Chitika