Commit 7c50554
committed
feat: add AtomicInteger example to demonstrate thread-safe counter
WHAT was added:
- Implemented `AtomicExample` with two threads incrementing a shared `AtomicInteger`.
- Each thread performs 1000 increments; final result is guaranteed to be 2000.
- Demonstrates atomic operations (`incrementAndGet`) vs. non-atomic counter++.
WHY this matters:
- In multithreaded environments, `counter++` is not atomic (read + add + write).
- Using a plain `volatile int` only ensures visibility, not atomicity → lost updates.
- `AtomicInteger` provides lock-free, thread-safe operations using Compare-And-Swap (CAS).
- This ensures correctness without the overhead of `synchronized`.
HOW it works:
1. Create an `AtomicInteger counter = new AtomicInteger(0)`.
2. Start two threads, each incrementing counter 1000 times.
3. `incrementAndGet()` ensures each increment is atomic.
4. Final result is always 2000, unlike volatile int (unpredictable) or synchronized (heavier).
REAL-LIFE APPLICATIONS:
- Web servers → counting active users or requests safely across multiple threads.
- Banking systems → tracking transactions without race conditions.
- Metrics/Monitoring → maintaining counters for errors, API hits, or performance stats.
- Concurrent data structures (e.g., ConcurrentHashMap) internally use atomic variables for efficiency.
- Gaming/Simulation engines → shared score counters or physics computations.
ALTERNATIVES & COMPARISON:
- volatile int → ensures visibility but not atomicity → unsafe for counter.
- synchronized → ensures atomicity & visibility but adds lock contention (slower).
- AtomicInteger → ensures atomicity & visibility, lock-free (faster under low/moderate contention).
KEYWORDS:
atomicity, CAS (Compare-And-Swap), race condition prevention, lock-free concurrency, volatile vs synchronized vs AtomicInteger.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b16de06 commit 7c50554
File tree
1 file changed
+47
-0
lines changed- Section19MultiThreading/Volatile and Atomic/src
1 file changed
+47
-0
lines changedLines changed: 47 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
1 | 3 | | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
2 | 31 | | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
0 commit comments