
Written on 27th April 2026 by Carter Phan.
Series
Data race = nhiều thread truy cập cùng dữ liệu + có ít nhất 1 thread ghi → kết quả sai
2 threads cùng đọc/ghi 1 biến shared
→ không có synchronization
→ kết quả unpredictable ❌
intcount=0;
ThreadA:count++;
ThreadB:count++;
count++ = read → +1 → write
Time →
Initial: count = 0
T1: read count (0)
T2: read count (0)
T1: write 1
T2: write 1
Final = 1 ❌ (expected 2)
Data race xảy ra khi:
Chỉ cho 1 thread vào critical section
synchronized(this) {
count++;
}
Time →
T1: lock → count++ → unlock
T2: wait → lock → count++ → unlock
Final = 2 ✔
Mutual exclusion = loại bỏ data race
Đoạn code truy cập shared resource
count++;
👉 Phải được bảo vệ bằng lock
synchronized(obj) {
// critical section
}
✔ Simple
❌ Block thread
lock.lock();
try {
// critical
}finally {
lock.unlock();
}
✔ Flexible
✔ Timeout / tryLock
AtomicIntegercount=newAtomicInteger(0);
count.incrementAndGet();
✔ Fast
✔ No blocking
| Method | Pros | Cons |
| synchronized | Simple, safe | Block, low performance |
| Lock | Flexible | Complex |
| Atomic | Fast | Limited use |
T1 giữ lock A → chờ B
T2 giữ lock B → chờ A
→ stuck ❌