Friday 5 October 2012

Atomicity in Java's double and long !

 Everybody knows that java has lots of primitive data types like byte, int, float, long, double, etc.

 Can we use these primitive variables in a multi threaded programming environment? The answer is 'YES' provided you have knowledge on atomicity and synchronization.

Atomicity is a very simple concept. Consider you have an integer variable named counter and you want to increment its value by one. So normal way to achieve this by using '++count' and this will work perfectly fine in a single threaded environment. But if you observe closely this '++count' operation, we can see that it is a compound operation. '++ count' is composed of three independent operations i.e. Read (The variable is read from the memory) + Modify (Increment the variable by 1) + Write (Update the new value to the memory location). So if you want to increment count by one in a multithreaded environment, we have to make these three operations to be atomic (occurs in one shot). How can we achieve this? Very simple surround the '++count' operation in a synchronized block or instead of int data type use AtomicInteger from java.util.concurrent.atomic package.

 Here is the key point of this article. Almost all the primitive variables Read and Write operations are atomic except for long and double. Since long and double are of 64 bit size, JVM is permitted to treat a 64 bit read or write as two separate operations i.e. while reading a long or double, JVM first read the first 32 bit and then read the second 32 bit and this constitute two distinct atomic operations for a read operation. Similar is the case of a write operation.

 So in conclusion, it is not safe to use mutable long and double variables in a multi threaded program without proper synchronization methods.

Hope this Helps!!

No comments:

Post a Comment