Skip to content

Commit c8923e2

Browse files
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

1 file changed

+1
-1
lines changed

Section19MultiThreading/Volatile and Atomic/src/VolatileExample.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ public static void main(String[] args) {
5252

5353
/*
5454
Detailed Explanation:
55-
------------------------
55+
5656
1. Har thread ke paas apna ek CPU cache hota hai.
5757
By default, variables main memory se copy hoke thread ke cache me stored hote hain.
5858

0 commit comments

Comments
 (0)