Skip to content

Commit

Permalink
add unit tests and fix
Browse files Browse the repository at this point in the history
  • Loading branch information
Roiocam committed Aug 16, 2024
1 parent ac62cce commit 6bc39a5
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/main/java/io/lettuce/core/protocol/SharedLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ class SharedLock {

private final Lock lock = new ReentrantLock();

private final ThreadLocal<Integer> sharedCnt = ThreadLocal.withInitial(() -> 0);

private volatile long writers = 0;

private volatile Thread exclusiveLockOwner;
Expand All @@ -45,6 +47,7 @@ void incrementWriters() {

if (WRITERS.get(this) >= 0) {
WRITERS.incrementAndGet(this);
sharedCnt.set(sharedCnt.get() + 1);
return;
}
}
Expand All @@ -63,6 +66,7 @@ void decrementWriters() {
}

WRITERS.decrementAndGet(this);
sharedCnt.set(sharedCnt.get() - 1);
}

/**
Expand Down Expand Up @@ -113,6 +117,7 @@ <T> T doExclusive(Supplier<T> supplier) {
private void lockWritersExclusive() {

if (exclusiveLockOwner == Thread.currentThread()) {
WRITERS.decrementAndGet(this);
return;
}

Expand All @@ -124,6 +129,11 @@ private void lockWritersExclusive() {
exclusiveLockOwner = Thread.currentThread();
return;
}
// reentrant exclusive lock
if (WRITERS.compareAndSet(this, sharedCnt.get(), -1)) {
exclusiveLockOwner = Thread.currentThread();
return;
}
}
} finally {
lock.unlock();
Expand All @@ -136,7 +146,7 @@ private void lockWritersExclusive() {
private void unlockWritersExclusive() {

if (exclusiveLockOwner == Thread.currentThread()) {
if (WRITERS.compareAndSet(this, -1, 0)) {
if (WRITERS.compareAndSet(this, -1, sharedCnt.get())) {
exclusiveLockOwner = null;
}
}
Expand Down
43 changes: 43 additions & 0 deletions src/test/java/io/lettuce/core/protocol/SharedLockTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package io.lettuce.core.protocol;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class SharedLockTest {

@Test
public void safety_on_reentrant_lock_exclusive_on_writers() throws InterruptedException {
final SharedLock sharedLock = new SharedLock();
CountDownLatch cnt = new CountDownLatch(1);
try {
// 共享锁
sharedLock.incrementWriters();

String result = sharedLock.doExclusive(() -> {
return sharedLock.doExclusive(() -> {
return "ok";
});
});
if ("ok".equals(result)) {
cnt.countDown();
}
} finally {
sharedLock.decrementWriters();
}

cnt.await(1, TimeUnit.SECONDS);

// verify writers won't be negative after finally decrementWriters
String result = sharedLock.doExclusive(() -> {
return sharedLock.doExclusive(() -> {
return "ok";
});
});

Assertions.assertEquals("ok", result);
}

}

0 comments on commit 6bc39a5

Please sign in to comment.