Middle+
What is the volatile keyword in Java and how is it used?
sobes.tech AI
Answer from AI
volatile guarantees the visibility of variable changes to all threads.
- Visibility guarantee: When one thread modifies a
volatilevariable, other threads are guaranteed to see this change. Withoutvolatile, changes may remain in the thread's cache and not synchronize with main memory. - Non-atomicity:
volatiledoes not guarantee atomicity of operations. Operations like increment (i++) are not atomic and can lead to race conditions even withvolatile.
Used for:
- State flags: When one thread sets a flag to inform other threads about some state.
- Single read/write operations: When operations on a variable involve a single write by one thread and multiple reads by others.
Example of using a flag:
// Example of using volatile for a termination flag
public class VolatileExample {
private volatile boolean terminated = false;
public void start() {
new Thread(() -> {
while (!terminated) {
// Thread work
System.out.println("Thread is running...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Thread finished.");
}).start();
}
public void stop() {
terminated = true; // Changing the volatile variable
}
public static void main(String[] args) throws InterruptedException {
VolatileExample example = new VolatileExample();
example.start();
Thread.sleep(500);
example.stop();
}
}