Skip to content

Commit

Permalink
apply suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
Roiocam committed Aug 30, 2024
1 parent c3db27f commit 6b66efb
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions src/main/java/io/lettuce/core/protocol/SharedLock.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class SharedLock {

private final Lock lock = new ReentrantLock();

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

private volatile long writers = 0;

Expand All @@ -47,7 +47,7 @@ void incrementWriters() {

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

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

/**
Expand Down Expand Up @@ -125,12 +125,8 @@ private void lockWritersExclusive() {
try {
for (;;) {

if (WRITERS.compareAndSet(this, 0, -1)) {
exclusiveLockOwner = Thread.currentThread();
return;
}
// reentrant exclusive lock
if (WRITERS.compareAndSet(this, sharedCnt.get(), -1)) {
// allow reentrant exclusive lock by comparing writers count and threadWriters count
if (WRITERS.compareAndSet(this, threadWriters.get(), -1)) {
exclusiveLockOwner = Thread.currentThread();
return;
}
Expand All @@ -147,7 +143,7 @@ private void unlockWritersExclusive() {

if (exclusiveLockOwner == Thread.currentThread()) {
// check exclusive look not reentrant first
if (WRITERS.compareAndSet(this, -1, sharedCnt.get())) {
if (WRITERS.compareAndSet(this, -1, threadWriters.get())) {
exclusiveLockOwner = null;
return;
}
Expand Down

0 comments on commit 6b66efb

Please sign in to comment.