The volatilekeyword in Java is used to indicate that a variable's value will be modified by different threads. It ensures that changes to the variable are always visible to other threads, providing a lightweight synchronization mechanism.
Here's a detailed explanation of its purpose and usage:
Visibility: When a variable is declared as volatile, it guarantees that any thread that reads the field will see the most recently written value. This is because the value of a
volatile variable is always read from and written to the main memory, bypassing the local cache.
Atomicity: The volatile keyword ensures visibility but does not guarantee atomicity. Operations on
volatile variables are not atomic, which means operations like incrementing a variable (count++) are not thread-safe with
volatile alone. If you need atomicity, you should use synchronized blocks or classes from the
java.util.concurrent.atomic package (e.g., AtomicInteger).
Instruction Reordering: The Java Memory Model allows the JVM to reorder instructions for performance optimization. However,
volatile prevents certain types of reordering, ensuring a happens-before relationship between the write and read of the
volatile variable. This means that changes made by one thread before writing to a
volatile the variable is visible to other threads that subsequently read that
volatile variable.
Example -
public class VolatileExample {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
// perform some work
}
}
public static void main(String[] args) {
VolatileExample example = new VolatileExample();
Thread t1 = new Thread(example::run);
t1.start();
// Let the thread run for a while
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Stop the running thread
example.stop();
}
}
When to Use volatile
Use volatile when you need to ensure visibility of changes to variables across threads, but only if:
The variable is accessed by multiple threads.
The variable is not involved in compound actions (like count++), which require atomicity.
You need to avoid the overhead of synchronization for simple flags or state indicators.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Here's a detailed explanation of its purpose and usage:
Visibility: When a variable is declared as
volatile, it guarantees that any thread that reads the field will see the most recently written value. This is because the value of avolatilevariable is always read from and written to the main memory, bypassing the local cache.Atomicity: The
volatilekeyword ensures visibility but does not guarantee atomicity. Operations onvolatilevariables are not atomic, which means operations like incrementing a variable (count++) are not thread-safe withvolatilealone. If you need atomicity, you should usesynchronizedblocks or classes from thejava.util.concurrent.atomicpackage (e.g.,AtomicInteger).Instruction Reordering: The Java Memory Model allows the JVM to reorder instructions for performance optimization. However,
volatileprevents certain types of reordering, ensuring a happens-before relationship between the write and read of thevolatilevariable. This means that changes made by one thread before writing to avolatilethe variable is visible to other threads that subsequently read thatvolatilevariable.Example -
When to Use
volatileUse
volatilewhen you need to ensure visibility of changes to variables across threads, but only if:count++), which require atomicity.