Skip to content

The RedisLockRegistry unlock race condition on the interrupted threadΒ #11049

Closed

Description

@artembilan

The current logic is like this:

		@Override
		public final void unlock() {
			if (!this.localLock.isHeldByCurrentThread()) {
				throw new IllegalStateException("You do not own lock at " + this.lockKey);
			}
			if (this.localLock.getHoldCount() > 1) {
				this.localLock.unlock();
				return;
			}
			try {
				if (Thread.currentThread().isInterrupted()) {
					RedisLockRegistry.this.executor.execute(this::removeLockKey);
				}
				else {
					removeLockKey();
				}

				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Released lock; " + this);
				}
			}
			catch (Exception e) {
				ReflectionUtils.rethrowRuntimeException(e);
			}
			finally {
				this.localLock.unlock();
			}
		}

Where it is very visible that this.localLock.unlock(); might be called before Redis key is removed in case of interrupted thread.

We cannot get rid of thread shifting since Redis driver does not allow to perform network operations on the interrupted thread. And we also cannot simply rely on the CountDownLatch or Future since they throw InterruptedException immediately in the access to them.

However there is "gotcha" in Java on the matter.
We can do like this:

CountDownLatch latch = new CountDownLatch(1);

this.executor.execute(() -> {
            try {
                removeLockKey();
            } finally {
                latch.countDown();
            }
});
        
boolean interrupted = false;
try {
            while (true) {
                try {
                    latch.await();
                    break; 
                } catch (InterruptedException e) {
                    interrupted = true; 
                }
            }
} finally {
            if (interrupted) {
                Thread.currentThread().interrupt(); 
            }
}

The JVM implicitly CLEARS the thread's interrupt flag when throwing an InterruptedException. We record it here with the interrupted flag, loop back to the latch.await() and restore Thread.currentThread().interrupt() state.

Activity

  1. added this to the 7.1.0 milestone on Jun 4, 2026
  2. added theissue type on Jun 4, 2026
  3. added a commit that references this issue on Jun 8, 2026
  4. added a commit that references this issue on Jun 8, 2026
  5. added 2 commits that reference this issue on Jun 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions