What is the use of volatile keyword?

The modifier ‘volatile’ informs the compiler that the value of a variable can be modified in ways that aren’t expressly stated by the program. The address of a global variable, for example, maybe given to the operating system’s clock function and used to keep track of the system time.
The contents of the variable are changed in this case without any explicit assignment lines in the program.
This is significant because most C compilers optimize some formulas by assuming that if a variable does not appear on the left side of an assignment statement, its content will not change. As a result, it is unlikely to be reexamined each time it is referred to. Additionally, some compilers alter the order in which an expression is evaluated throughout the compilation process. These modifications are prevented by the volatile modifier.

Volatile is a keyboard which added in Java 5.Once you declare a variable as a volatile the value of the variable directly return to the main memory instead of storing CPU cache.

With non-volatile variables there are no guarantees about when the Java Virtual Machine (JVM) reads data from main memory into CPU caches, or writes data from CPU caches to main memory. This can cause several problems like it might be possible we’ll not get correct value of the variable because you are reading and writing the variable from CPU cache and difference CPU have its own cache and its own values but if you are define variable as a volatile then value will be read from main memory and write into main memory so we will get correct value