Check-Then-Act Race Conditions
You'll learn about a subtle race condition pattern where checking and acting on a condition happen in separate, non-atomic steps.
The Core Idea
A check-then-act race condition occurs when one thread checks a condition (like "is the cache empty?"), decides what to do based on that check, but before it can act, another thread changes the underlying state. The first thread then acts on outdated information, leading to incorrect behavior.
This is different from the simple lost update problem. Here, the race happens between reading state to make a decision and executing that decision.
A Real-World Analogy
Imagine checking your fridge, seeing it's empty, and deciding to go grocery shopping. While you're getting your keys, your roommate also checks, finds it empty, and leaves to shop. Now you both waste time buying duplicate groceries—because the check and the act (leaving to shop) weren't atomic.
The Pattern in Code
class LazyCache {
private ExpensiveObject cache = null;
public ExpensiveObject getInstance() {
if (cache == null) { // CHECK
// Another thread might execute here!
cache = new ExpensiveObject(); // ACT
}
return cache;
}
}
If two threads call getInstance() simultaneously, both might see cache == null, both pass the check, and both create a new ExpensiveObject—defeating the lazy initialization pattern and potentially causing serious bugs if the object shouldn't be duplicated.
Why It Matters
Check-then-act is everywhere: lazy initialization, singleton patterns, conditional updates, resource allocation. Without synchronization, the gap between checking and acting creates a window for another thread to invalidate your assumptions.
Key Takeaway: Check-then-act race conditions occur when the time gap between checking a condition and acting on it allows another thread to change the state, causing the action to be based on stale information. The check and act must be atomic.