jersey icon indicating copy to clipboard operation
jersey copied to clipboard

Fix race condition in AsyncResponder.resume() and cancel() by re-checking state under write lock

Open anuragg-saxenaa opened this issue 7 months ago • 0 comments

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

  1. Thread A (resume()): acquires read lock → sees SUSPENDED → releases read lock
  2. Thread B (cancel()): acquires read lock → sees SUSPENDED → releases read lock
  3. Thread A: acquires write lock → sets RESUMED → releases write lock → processes response
  4. 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

anuragg-saxenaa avatar Apr 13 '26 14:04 anuragg-saxenaa