Skip to content

What are the practical uses of volatile modifiers?

Posted in Education, and WhoCodeFirst

One of the practical use of the volatile variable is to make reading double and long atomic.

Both double and long are 64-bit wide and they are read in two parts, first 32-bit first time and next 32-bit second time, which is non-atomic but volatile double and long read is atomic in Java.

Another use of the volatile variable is to provide a memory barrier, just like it is used in the Disrupter framework.

Basically, Java Memory model inserts a write barrier after you write to a volatile variable and a read barrier before you read it.

Which means, if you write to volatile field then it’s guaranteed that any thread accessing that variable will see the value you wrote and anything you did before doing that right into the thread is guaranteed to have happened and any updated data values will also be visible to all threads, because the memory barrier flushed all other writes to the cache.

Happy Learning! 😇

Translate »