Skip to content

Commit d441b81

Browse files
committed
docs(concurrency): add detailed comparison of volatile and AtomicInteger in Java
What - Added documentation explaining differences between `volatile` and `AtomicInteger` in multithreaded programming. - Covered: 1. **Volatile** - Guarantees visibility (reads/writes go to main memory). - Does not guarantee atomicity. - Example: `volatile int count = 0;` → `count++` is not atomic and can lead to lost updates. 2. **AtomicInteger** - Provides atomic operations (`incrementAndGet()`, `compareAndSet()`). - Lock-free, CAS-based, ensuring both visibility and atomicity. - Example: `AtomicInteger count = new AtomicInteger(0);` → `count.incrementAndGet()` ensures safe increments. 3. **When to Use** - Use `volatile` for flags (simple read/write state variables). - Use `AtomicInteger` for counters or shared mutable integers requiring atomic updates. Why - Clarifies a common misconception: that `volatile` alone ensures thread-safety. - Highlights that atomicity requires `AtomicInteger` (or synchronization), not just visibility. - Provides practical guidance on choosing between the two. Logic - **Volatile semantics**: read/write operations are always visible to all threads immediately, but compound actions like `count++` are still unsafe because they break into multiple non-atomic steps (read → increment → write). - **AtomicInteger semantics**: all key operations (increment, compare-and-swap) are atomic, leveraging CPU-level CAS instructions. No race conditions occur. - **Decision point**: - Use `volatile` when you only need a one-way signal or visibility guarantee. - Use `AtomicInteger` when multiple threads must safely modify a shared counter without locking. Key Takeaways ✔ `volatile` → visibility only, not atomicity. ✔ `count++` with `volatile` can lose updates under concurrency. ✔ `AtomicInteger` → provides lock-free atomic operations with visibility. ✔ Ideal for counters, accumulators, and CAS logic. ✔ Use `volatile` for flags (boolean control variables), not for shared mutable counters. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 8180e70 commit d441b81

File tree

2 files changed

+69
-37
lines changed

2 files changed

+69
-37
lines changed

JAVA8/🧠 volatile vs AtomicInteger in Java.txt

Lines changed: 0 additions & 37 deletions
This file was deleted.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
Volatile vs AtomicInteger in Java:
2+
3+
1. Volatile
4+
- volatile is a Java keyword used to mark a variable so that:
5+
- Reads and writes go directly to main memory (no thread-local caching).
6+
- Visibility is guaranteed: when one thread updates a volatile variable,
7+
other threads see the updated value immediately.
8+
9+
What it does:
10+
- Ensures **visibility** across threads.
11+
12+
What it does not do:
13+
- Does NOT ensure **atomicity**.
14+
- Operations like count++ are not atomic, since they involve
15+
read → modify → write.
16+
17+
Example where volatile fails:
18+
19+
volatile int count = 0;
20+
21+
public void increment() {
22+
count++; // Not atomic: multiple threads may overwrite each other.
23+
}
24+
25+
Problem:
26+
- If two threads read the same value of count (say 10),
27+
both increment and write back 11, losing one update.
28+
29+
2. AtomicInteger
30+
- AtomicInteger is part of `java.util.concurrent.atomic` package.
31+
- Provides atomic operations such as:
32+
- incrementAndGet()
33+
- getAndIncrement()
34+
- compareAndSet()
35+
36+
- Ensures **atomicity** and **thread safety** without explicit synchronization.
37+
- Uses lock-free, non-blocking CAS (Compare-And-Swap) under the hood.
38+
39+
Example with AtomicInteger:
40+
41+
import java.util.concurrent.atomic.AtomicInteger;
42+
43+
AtomicInteger count = new AtomicInteger(0);
44+
45+
public void increment() {
46+
count.incrementAndGet(); // Atomic and thread-safe
47+
}
48+
49+
Behavior:
50+
- Each thread increments safely.
51+
- No lost updates.
52+
- Faster than synchronized methods in many cases.
53+
54+
3. When to Use What?
55+
- Use volatile when:
56+
- You only need a **flag** (true/false, ready/done).
57+
- You just care about visibility of a single write/read.
58+
- Example: volatile boolean isRunning;
59+
60+
- Use AtomicInteger when:
61+
- You need **atomic operations** like counting, accumulating,
62+
or compare-and-set in multi-threaded contexts.
63+
- Example: safely counting user requests in a server.
64+
65+
66+
67+
- volatile → Guarantees visibility, but not atomicity.
68+
- AtomicInteger → Guarantees both visibility and atomicity for integer operations, using efficient
69+
CAS-based lock-free mechanisms.

0 commit comments

Comments
 (0)