0 votes
in Java by
What is volatile keyword in java? And when to use volatile in Java?

1 Answer

0 votes
by (4.4k points)
Volatile keyword is used for marking a Java variable as "stored in main memory". Every read operation of volatile variable will be read from the computer's main memory, and not from the CPU cache. And every write operation of a volatile variable will be written to main memory, and not in CPU cache.

Volatile is used to indicate that a variable's value will be modified by different threads. The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory".

A Volatile variable is modified asynchronously by concurrently running threads in a Java application. It does not allowed to store local copy of a variable that is different from the value currently held in "main" memory.

When a field is declared volatile, the compiler and runtime are put on notice that this variable is shared. And operations on it should not be reordered with other memory operations.Volatile variables are not cached in registers or in caches where they are hidden from other processors, so a read of a volatile variable always returns the most recent write by any thread.

Share:- Whatsapp Facebook Facebook

Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.