Skip to content

Commit b16de06

Browse files
committed
feat: add thread-safe counter using AtomicInteger to ensure atomicity
WHAT was added: - Implemented `VolatileCounter` class with a shared `AtomicInteger counter`. - Two threads increment the counter 1000 times each. - Final value is guaranteed to be 2000 due to atomic increments. - Demonstrates why `volatile` alone is not sufficient for compound operations like counter++. WHY this matters: - Concurrency introduces race conditions when multiple threads update shared variables. - `volatile` ensures visibility (threads see the latest value) but does not ensure atomicity. Example: counter++ = read + add + write (3 steps). These can interleave and cause lost updates. - `AtomicInteger` provides atomic operations (`incrementAndGet`, `getAndAdd`) using Compare-And-Swap (CAS). - CAS is lock-free and more efficient than `synchronized` for simple counters. HOW it works: 1. `counter` is an `AtomicInteger` initialized to 0. 2. Two threads call `vc.increment()` 1000 times each. 3. `incrementAndGet()` ensures the entire increment is atomic. 4. After `join()`, final output is always 2000. 5. Contrast: - With plain `volatile int counter`, final result < 2000 (due to lost updates). - With `synchronized`, result = 2000 but at the cost of heavier locking. REAL-LIFE APPLICATIONS: - Web servers → counting active requests or total hits safely across threads. - Logging systems → counting error/warning occurrences without locks. - Metrics & monitoring → real-time counters in Prometheus or similar systems. - Banking apps → tracking transactions or balance updates safely. - Producer-consumer queues → keeping track of queue size in multithreaded systems. LIMITATIONS: - `AtomicInteger` only solves atomicity for a single variable. - For multiple related variables (e.g., debit & credit together), atomic classes are not enough — use locks or higher-level constructs. - High contention can reduce CAS efficiency, though still generally faster than synchronization. KEYWORDS: volatile vs synchronized vs AtomicInteger, atomicity, CAS (Compare-And-Swap), lock-free concurrency, thread-safe counter. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent a12e011 commit b16de06

File tree

1 file changed

+11
-24
lines changed

1 file changed

+11
-24
lines changed
Lines changed: 11 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,14 @@
11
import java.util.concurrent.atomic.AtomicInteger;
22

33
public class VolatileCounter {
4-
54
private AtomicInteger counter = new AtomicInteger(0);
65

76
public void increament(){
87
counter.incrementAndGet();
9-
10-
/*private volatile int counter = 0;
11-
12-
public void increament(){
13-
counter++;
14-
*/
15-
168
}
179

18-
/*
19-
synchronized
20-
21-
Remove this synchronized and check the output.
22-
othewise add volatile to the counter. Still not get 2000 using volatile.
23-
Isko Bolte Atomicity. Har ek operation isolated rahe.
24-
Java provides class to ensure a atomic city. like
25-
atomic integer, atomic long, atomic boolean without using lock to achive isolationa and atomiccity
26-
*/
27-
28-
public int getCounter(){
10+
public int getCounter() {
2911
return counter.get();
30-
31-
/* return counter;*/
3212
}
3313

3414
public static void main(String[] args) throws InterruptedException {
@@ -47,10 +27,17 @@ public static void main(String[] args) throws InterruptedException {
4727

4828
t1.start();
4929
t2.start();
50-
5130
t1.join();
5231
t2.join();
53-
5432
System.out.println(vc.getCounter());
5533
}
56-
}
34+
}
35+
36+
/*
37+
Synchronized:
38+
Remove this synchronized and check the output.
39+
othewise add volatile to the counter. Still not get 2000 using volatile.
40+
Isko Bolte Atomicity. Har ek operation isolated rahe.
41+
Java provides class to ensure a atomic city. like
42+
atomic integer, atomic long, atomic boolean without using lock to achive isolationa and atomiccity
43+
*/

0 commit comments

Comments
 (0)