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
- Reading the current value of i
- Increment the current value of i
- 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
- Thread A: Retrieve c.
- Thread B: Retrieve c.
- Thread A: Increment retrieved value; result is 1.
- Thread B: Decrement retrieved value; result is -1.
- Thread A: Store result in c; c is now 1.
- 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!...
If you know anyone who has started learning Java, why not help them out! Just share this post with them.
Thanks for studying today!...
Explanation is clear and easy to understand.
ReplyDeleteNice Blog, i hope gather more information about java.thanks for sharing your idea.
ReplyDeleteJava Online Training
Java Online Training In Chennai
Core Java Online Training