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.