What Is the Purpose of Java’s volatile Keyword?
The volatile keyword in Java ensures visibility of changes across threads.
Visibility in Multithreading
Volatile ensures that updates to a variable are visible to all threads immediately.
Example Code
volatile boolean isRunning = true;
Thread thread = new Thread(() -> {
while (isRunning) {
// perform task
}
});
thread.start();
isRunning = false; // Stops the thread
This example shows how volatile controls visibility of variables between threads.
Leave a Reply