Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does volatile ever block or involve a context switch?

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?

like image 772
chrisapotek Avatar asked Feb 27 '12 16:02

chrisapotek


3 Answers

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

like image 104
John Vint Avatar answered Oct 15 '22 07:10

John Vint


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.

like image 38
Gray Avatar answered Oct 15 '22 06:10

Gray


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.

like image 22
Tudor Avatar answered Oct 15 '22 06:10

Tudor