Reputation: 2825
I've been told that the use of a volatile variable is much more efficient than using a synchronized block whenever using it (read or write).
Up until Java 1.4 I can see why (because then threads didn't have to flush and refresh all accessible memory).
But since Java 1.5, the only difference I see between using volatile variable and a synchronized block - is the lock acquiring mechanism.
Is acquiring the lock really that expensive? And if so, why is that?
Upvotes: 5
Views: 222
Reputation: 2444
volatile variable and synchronization are different tools for synchronization. Its not ideal to compare the performances of these too.
Volatile - http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5 - In a way it is there to address issues like visibility of variable and reordering of instructions.
Synchronization - Its totally a different giant. It guarantees atomicity along with taking care of reordering and visibility. In order to achieve Atomicity it has to do lots of book keeping.
Therefore synchronization is expensive then read or write of a volatile variable. To be fair you ought to compare different mechanism of synchronization and different type of locks i.e ReaderWriterLock, StampedLock, also study about CompareAndSwap its a good read.
Upvotes: 1
Reputation: 2579
The "expense" is because of it reading from memory every time, instead of possibly using the memory caches. It is not a lot, at least on x86 machines.
Upvotes: 1