At work today, I came across the volatile
keyword in Java. Not being very familiar with it, I found this explanation.
Given the detail in which that arti
A variable declared with volatile
keyword, has two main qualities which make it special.
If we have a volatile variable, it cannot be cached into the computer's(microprocessor) cache memory by any thread. Access always happened from main memory.
If there is a write operation going on a volatile variable, and suddenly a read operation is requested, it is guaranteed that the write operation will be finished prior to the read operation.
Two above qualities deduce that
And on the other hand,
volatile
keyword is an ideal way to maintain a shared variable which has 'n' number of reader threads and only one writer thread to access it. Once we add the volatile
keyword, it is done. No any other overhead about thread safety.Conversly,
We can't make use of volatile
keyword solely, to satisfy a shared variable which has more than one writer thread accessing it.