Commit c8923e2
committed
feat: add VolatileExample demonstrating visibility with volatile keyword
WHAT was added:
- A new class `VolatileExample` with nested `SharedObject`.
- Demonstrates how `volatile` ensures visibility across threads.
- Writer thread sets a flag to `true` after 3 seconds.
- Reader thread busy-waits until it sees the updated flag.
WHY this matters:
- Explains a subtle concurrency issue: CPU caches may hide updates between threads.
- Without `volatile`, reader thread may loop forever (stale value).
- With `volatile`, changes are written to and read from main memory directly.
- Useful to show lighter alternative to full synchronization when only visibility is needed.
HOW it works:
1. `SharedObject` has a `volatile boolean flag`.
2. Writer thread: sleeps 3 seconds → sets flag = true.
3. Reader thread: spin-waits until `flag` becomes true.
4. Because of `volatile`, the reader observes the writer’s update immediately.
Key Concepts:
- CPU caches can cause stale reads.
- `volatile` guarantees visibility (but not atomicity).
- Difference between visibility and atomicity in concurrency.
REAL-LIFE APPLICATIONS:
- Thread stop signals → e.g., a game loop thread checks a `volatile isRunning` flag.
- Configuration reload → one thread updates config values, other threads immediately see changes.
- Monitoring systems → flags for shutting down services gracefully (without locking).
- Producer-consumer light signaling → producer sets a flag once data is ready, consumers wake up instantly.
- Logging frameworks → enable/disable logging dynamically across threads without restarting the app.
LIMITATIONS:
- `volatile` does NOT make compound actions (like increment) atomic.
- For atomic operations, use `synchronized` or `java.util.concurrent.atomic` classes.
KEYWORDS:
volatile visibility cpu-cache spin-wait memory-barrier thread-communication.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent fc8498e commit c8923e2
File tree
1 file changed
+1
-1
lines changed- Section19MultiThreading/Volatile and Atomic/src
1 file changed
+1
-1
lines changedLines changed: 1 addition & 1 deletion
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
52 | 52 | | |
53 | 53 | | |
54 | 54 | | |
55 | | - | |
| 55 | + | |
56 | 56 | | |
57 | 57 | | |
58 | 58 | | |
| |||
0 commit comments