capypad
0 day streak
java / intermediate
Snippet

Memory Visibility with the volatile Keyword

The volatile keyword ensures that changes to a variable are always visible to all threads immediately. It prevents threads from caching the variable locally, ensuring they always read the latest value from main memory.

snippet.java
java
1
2
3
4
5
6
7
8
9
public class SharedFlag {
private volatile boolean active = true;
 
public void stop() { active = false; }
 
public void work() {
while (active) { /* perform task */ }
}
}
Breakdown
1
private volatile boolean active
Ensures any write to 'active' is visible to other threads reading it without needing explicit synchronization.
2
while (active)
The loop will correctly terminate even if another thread calls stop(), as it always checks the main memory.