Skip to content

Commit 7c50554

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

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,49 @@
1+
import java.util.concurrent.atomic.AtomicInteger;
2+
13
public class AtomicExample {
4+
public static void main(String[] args) throws InterruptedException {
5+
// AtomicInteger: ek atomic counter jo thread-safe hai
6+
AtomicInteger counter = new AtomicInteger(0);
7+
8+
// Thread 1: increments 1000 times
9+
Thread t1 = new Thread(() -> {
10+
for (int i = 0; i < 1000; i++) {
11+
counter.incrementAndGet(); // atomic increment
12+
}
13+
});
14+
15+
// Thread 2: increments 1000 times
16+
Thread t2 = new Thread(() -> {
17+
for (int i = 0; i < 1000; i++) {
18+
counter.incrementAndGet(); // atomic increment
19+
}
20+
});
21+
22+
t1.start();
23+
t2.start();
24+
25+
t1.join();
26+
t2.join();
27+
28+
//Final result always 2000 (race condition nahi hoga)
29+
System.out.println("Final counter value: " + counter.get());
30+
}
231
}
32+
33+
/*
34+
Why AtomicInteger?
35+
- Agar simple int + volatile use karte:
36+
counter++;
37+
Yeh do steps hai: read -> add -> write
38+
Multiple threads me lost updates ho jaati hai (result unpredictable).
39+
40+
- AtomicInteger methods:
41+
- incrementAndGet() -> ++counter (atomic)
42+
- getAndIncrement() -> counter++ (atomic)
43+
- addAndGet(n) -> counter += n (atomic)
44+
- get() -> safe read
45+
46+
- Internally, AtomicInteger CAS (Compare-And-Swap) ka use karta hai.
47+
Matlab ek hi thread successful hota hai update karne me,
48+
baaki retry karte hain.
49+
*/

0 commit comments

Comments
 (0)