Volatile keyword

Suppose If two thread are trying to access the same shared variable and are running on different processor/cpu, then the shared variable is cached in the processor local cache.If the first thread updates the variable, the second thread won’t be able to see the change because the variable is only update in the first processor cache and there is no guarantee that it will be updated in the second processor cpu. To avoid this issue volatile keyword is used.

When the volatile is added to a variable, it indicates that the variable should never be cached and hence the write will always update the value in main memory and the read will always get the latest value from the main memory. So, if one thread updates the variable, the other thread will be able to access the latest value.

Volatile can used only if a single thread is writing and multiple threads are reading the same variable or data. But if there are multiple reads / writes from different threads then synchronized / locks should be used.

Leave a Reply

Your email address will not be published. Required fields are marked *