Fix race condition in AsyncResponder.resume() and cancel() by re-checking state under write lock
Summary
ServerRuntime.AsyncResponder uses a read-check / release / write-acquire pattern in both resume() and cancel(). A window exists between releasing the read lock and acquiring the write lock where another thread can change the state, making the initial check stale. This allows concurrent resume() and cancel() calls to both proceed past the state check and both set state = RESUMED, resulting in double-processing of a response.
Race scenario
- Thread A (
resume()): acquires read lock → seesSUSPENDED→ releases read lock - Thread B (
cancel()): acquires read lock → seesSUSPENDED→ releases read lock - Thread A: acquires write lock → sets
RESUMED→ releases write lock → processes response - Thread B: acquires write lock → sets
RESUMED,cancelled = true→ processes response again
Fix
Add a second state check inside the write-lock critical section in both resume() and cancel(). If state changed between the read and write lock acquisitions, return false immediately. Also wrapped write-lock body in try/finally so the lock is always released even if an exception occurs in the re-check.
stateLock.writeLock().lock();
try {
// Re-check under write lock: another thread may have changed state
// between releasing the read lock and acquiring the write lock.
if (state != SUSPENDED) {
return false;
}
state = RESUMED;
} finally {
stateLock.writeLock().unlock();
}
This is the standard double-checked locking pattern for ReadWriteLock.
Fixes #6068