This is a very important foundational question.
If you truly understand “read shared data”, race conditions will start making sense everywhere.I’ll explain it from first principles, with plain language + real examples + mental model.
1️⃣ What Does “Shared Data” Mean?
Shared data is any data that can be accessed and modified by more than one execution at the same time.
Key word: more than one.
If two or more users / threads / services can:
- read it
- change it
? then it is shared data.
2️⃣ What Does “Read Shared Data” Mean?
It means:
One execution reads a value that another execution might also read or change at the same time.
That read becomes unsafe if it’s used to make decisions.
3️⃣ The Simplest Example (Non-Technical)
Imagine a whiteboard in an office:
Remaining tickets = 1
Two people look at it at the same time:
- Person A reads: 1
- Person B reads: 1
Both decide: “I can take one.”
❌ Problem: they read shared data without coordination
4️⃣ Database Example (Most Common)
Table: account
id | balance
1 | 100
Two users call:
withdraw(1, 70);
withdraw(1, 40);
Timeline:
Thread A reads balance → 100
Thread B reads balance → 100
This balance value is shared data.
Both threads now base decisions on the same stale value.
5️⃣ Why Reading Is Dangerous (Not Writing!)
Most people think:
“Writing causes problems.”
❌ Wrong.
The real danger is:
Reading shared data and then making a decision.
This pattern is dangerous:
if (balance >= amount) {
balance = balance - amount;
}
Because:
- balance might already be outdated
- Someone else may change it right after you read it
6️⃣ Another Example: Inventory System
Product: iPhone
Stock: 1
Two orders at the same time:
Thread A reads stock → 1
Thread B reads stock → 1
Both place order → oversold
? Stock count is shared data.
7️⃣ Shared Data Is Everywhere
| Data | Why it’s shared |
|---|---|
| DB rows | Multiple users |
| Cache values | Multiple instances |
| Files | Concurrent access |
| Counters | Multiple updates |
| Message offsets | Multiple consumers |
If more than one actor can touch it, it’s shared.
8️⃣ When Reading Shared Data Is SAFE ✅
Reading is safe only if:
- Data is immutable (never changes)
- Or data is protected by a lock
- Or read is followed by atomic update
Example:
UPDATE inventory
SET stock = stock - 1
WHERE product_id = 10 AND stock > 0;
This combines:
- Read
- Check
- Write
? into one atomic operation
9️⃣ Key Mental Model (MEMORIZE)
The moment you read shared data and make a decision, you have a race condition risk.
? One-Sentence Rule
Shared data + read-check-write without protection = guaranteed bug.
? Quick Self-Test
Ask yourself:
- Can two users read this value at same time?
- Can they both act on it?
- Who ensures only one wins?
If you can’t answer → shared data is unsafe.