Skip to content

Commit

Permalink
confirm won't blocking other thread
Browse files Browse the repository at this point in the history
  • Loading branch information
Roiocam committed Aug 16, 2024
1 parent a59045a commit c3db27f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/main/java/io/lettuce/core/protocol/SharedLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,13 @@ private void lockWritersExclusive() {
private void unlockWritersExclusive() {

if (exclusiveLockOwner == Thread.currentThread()) {
// check exclusive look not reentrant first
if (WRITERS.compareAndSet(this, -1, sharedCnt.get())) {
exclusiveLockOwner = null;
return;
}
// otherwise unlock until no more reentrant left
WRITERS.incrementAndGet(this);
}
}

Expand Down
17 changes: 16 additions & 1 deletion src/test/java/io/lettuce/core/protocol/SharedLockTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public void safety_on_reentrant_lock_exclusive_on_writers() throws InterruptedEx
sharedLock.decrementWriters();
}

cnt.await(1, TimeUnit.SECONDS);
boolean await = cnt.await(1, TimeUnit.SECONDS);
Assertions.assertTrue(await);

// verify writers won't be negative after finally decrementWriters
String result = sharedLock.doExclusive(() -> {
Expand All @@ -37,6 +38,20 @@ public void safety_on_reentrant_lock_exclusive_on_writers() throws InterruptedEx
});

Assertions.assertEquals("ok", result);

// and other writers should be passed after exclusive lock released
CountDownLatch cntOtherThread = new CountDownLatch(1);
new Thread(() -> {
try {
sharedLock.incrementWriters();
cntOtherThread.countDown();
} finally {
sharedLock.decrementWriters();
}
}).start();

await = cntOtherThread.await(1, TimeUnit.SECONDS);
Assertions.assertTrue(await);
}

}

0 comments on commit c3db27f

Please sign in to comment.