Monday, October 29, 2012

What is Atomic Operation in java?

Atomic means each action take place in one step without interruption or we can say that operation is performed as a single unit of work without the possibility of interference from other operations.
An Atomic operation cannot stop in the middle, either it happened completely or doesn't happen at all.

Java language specification guarantees that
  • Reading or writing of a variable/reference is atomic unless the variable is of type long or double.
  • Read and write are atomic for all variable declared volatile including long and double variables.

Atomic action can be used without fear of thread interference.
Using simple atomic variable access is more efficient than accessing the same variable through synchronized code. But it require more  care and attention from programmer to avoid memory consistency .
Example:
Operation i++;

This operation is not atomic as it happens in 3 steps
  1. Reading the current value of i
  2. Increment the current value of i
  3. Writing the new value of i

Since java 1.5, java language provides atomic variable e.g. AtomicInteger or AtomicLong which provides methods like
getAndDecrement(),getAndIncrement() and getAndSet() in java.util.concurrent.atomic package which are all atomic.

Example:

Counter class is designed so that invocation of increment () add 1 to the variable c and decrement () subtract 1 from c.
If Counter object is reference from multiple threads, interference b/w threads may prevent from happening as expected.

Suppose 2 thread are accessing the Counter object
  1. Thread A: Retrieve c.
  2. Thread B: Retrieve c.
  3. Thread A: Increment retrieved value; result is 1.
  4. Thread B: Decrement retrieved value; result is -1.
  5. Thread A: Store result in c; c is now 1.
  6. Thread B: Store result in c; c is now -1.


Thread A result is lost and overwritten by Thread B.
Under different circumstances, it might be Thread B result is lost and overwritten by Thread B, or there could be no error.

If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

2 comments: