volatile
- Java course
- Expert
- Lesson 9/46
- 5 min
Learn visible variables with volatile.
volatile and visibility
The volatile keyword makes every read of a field go straight to main memory. So a value written by one thread is seen immediately by others; no thread keeps a stale value in its own cache.
Example: volatile boolean ready. When one thread writes ready = true, another reading ready sees true. volatile gives only visibility; it does not by itself solve complex cases such as several threads writing at once, where synchronized is needed.
When volatile is enough
volatile is enough when a flag or a single variable is shared between threads. For example, if a ready flag is written and read, volatile makes the read see the latest value.
But read-modify-write operations such as count++ are not atomic; if two threads increment at once a value is lost. In such cases use synchronized or AtomicInteger. volatile guarantees only visibility, not atomicity.
Practice Visibility with a volatile flag
Write a Flag class with a volatile boolean ready field, a void set() method that does ready = true, and a boolean isReady() that returns ready. In main, create new Flag(), call set, and print the isReady result with System.out.println.
Starter code
// Define the Flag class
// Add a volatile ready field and set
// Print the result in mainSample solution
class Flag {
volatile boolean ready;
public void set() { ready = true; }
public boolean isReady() { return ready; }
}
public class VolatileDemo {
public static void main(String[] args) {
Flag f = new Flag();
f.set();
System.out.println(f.isReady());
}
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Declare a volatile field
private ____ boolean ready;
private volatile boolean ready;
Explanation: volatile gives the visibility guarantee.
2 Match the keywords
| Term | Meaning |
|---|---|
volatile |
Visibility |
synchronized |
Happens-before |
final |
Immutability |
new |
Heap allocation |
3 What does a volatile field guarantee?
- A single instance
- Runtime visibility Correct answer
- Class metadata
- Immutability
Explanation: volatile guarantees the field's visibility.