Race condition xảy ra khi nhiều thread truy cập shared data đồng thời, kết quả cuối phụ thuộc vào thứ tự thực thi — không thể đoán trước.
Ví dụ: hai thread cùng increment count mà không synchronize dẫn đến kết quả sai. Phòng tránh:
- synchronization (synchronized, Lock)
- atomic variables (
AtomicInteger) - immutable objects
- thread-safe collections (
CopyOnWriteArrayList). Nguyên nhân gốc rễ: non-atomic operations trên shared state. Test bằng cách tăng concurrency để expose lỗi