From 6b66efb61a111c03a892150884ee87836d87ac2a Mon Sep 17 00:00:00 2001 From: JingZhang Chen Date: Sat, 31 Aug 2024 04:29:02 +0800 Subject: [PATCH] apply suggestions --- .../io/lettuce/core/protocol/SharedLock.java | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/main/java/io/lettuce/core/protocol/SharedLock.java b/src/main/java/io/lettuce/core/protocol/SharedLock.java index f2e90186ee..c3ad425c16 100644 --- a/src/main/java/io/lettuce/core/protocol/SharedLock.java +++ b/src/main/java/io/lettuce/core/protocol/SharedLock.java @@ -26,7 +26,7 @@ class SharedLock { private final Lock lock = new ReentrantLock(); - private final ThreadLocal sharedCnt = ThreadLocal.withInitial(() -> 0); + private final ThreadLocal threadWriters = ThreadLocal.withInitial(() -> 0); private volatile long writers = 0; @@ -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; } } @@ -66,7 +66,7 @@ void decrementWriters() { } WRITERS.decrementAndGet(this); - sharedCnt.set(sharedCnt.get() - 1); + threadWriters.set(threadWriters.get() - 1); } /** @@ -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; } @@ -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; }