volatile keyword in Java

Volatile is a keyword in Java, which is used to write any changes to the variable directly into the main memory of the CPU instead of the local or cached memory of the CPU.

This keyword is useful when an application runs in multiple CPUs not Just in one CPU. When we use multiple CPUs the threads will copy the main memory into local cached memory of the CPU to improve the performance of an application or a thread.

In this circumstances when any thread changes the variable value then it will not reflect it into the main memory, the other thread which is running on different CPU will read from the main memory only not in the local memory. So, the main memory will have old value not the new value this may lead erroneous behavior of an application or a thread.

To avoid this kind of errors java have an inbuilt keyword which is a volatile.

The following is the declaration of the volatile.

public volatile String str;

volatile might lead to performances impact of an application or thread, why because every time read and write operation needs to be performed from the main memory not from the CPU local memory.

There is much more information about the volatile keyword usage, for now this is what we have covered