Initially I thought a volatile variable was better than synchronized keyword as it did not involve BLOCKING or CONTEXT SWITCHING. But reading this I am now confused.
Is volatile implemented in a non-blocking approach using low level atomic locks or no?
Is volatile implemented in a non-blocking approach using low level atomic locks or no?
Volatile's implementation varies between each processor but it is a non-blocking field load/store - it is usually implemented via memory-fences but can can also be managed with cache-coherent protocols.
I just read that post. That poster is actually incorrect in his explanations of Volatile vs Synchronized flow and someone corrected him as a comment. Volatile will not hold a lock, you may read that a volatile store is similar to a synchronized release and a volatile load is similar to a synchronized acquire but that only pertains to memory visibility and not actual implementation details
Is volatile implemented in a non-blocking approach using low level atomic locks or no?
Use of volatile
erects a memory barrier around the field in question. This does not cause a thread to be put into the "BLOCKING" state. However when the volatile
field is accessed, the program has to flush changes to central memory and update cache memory which takes cycles. It may result in a context switch but doesn't necessary cause one.
It's true that volatile
does not cause blocking.
However, the statement
a volatile variable was better than synchronized keyword as it did not involve BLOCKING or CONTEXT SWITCHING.
is very debatable and depends heavily on what you are trying to do. volatile
is not equivalent to a lock and declaring a variable volatile does not give any guarantees regarding the atomicity of operations in which that variable is involved e.g. increment.
What volatile
does is prevent the compiler and/or CPU from performing instruction reordering or caching of the specific variable. This is known as a memory fence. This nasty little mechanism is required to ensure that in a multithreaded environment all threads reading a specific variable have an up-to-date view of its value. This is called visibility and is different from atomicity.
Atomicity can only be guaranteed in the general case by the use of locks (synchronized
) or atomic primitives.
What can be however, confusing, is the fact that using synchronization mechanisms also generates an implicit memory fence, so declaring a variable volatile if you're only going to read/write it inside synchronized
blocks is redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With