From 699a3b8214b2b1b16a8fd05d1966e025897fc033 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 5 Mar 2025 18:31:27 +0800 Subject: [PATCH] =?UTF-8?q?=E9=94=81=E6=9C=BA=E5=88=B6=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/zfoo/scheduler/util/LazyCache.java | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java b/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java index f2e3083f..5faaa282 100644 --- a/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java +++ b/scheduler/src/main/java/com/zfoo/scheduler/util/LazyCache.java @@ -8,6 +8,7 @@ import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.BiConsumer; /** @@ -52,7 +53,6 @@ public class LazyCache { SIZE; } - private int maximumSize; private int backPressureSize; private long expireAfterAccessMillis; @@ -62,6 +62,7 @@ public class LazyCache { private ConcurrentMap> cacheMap; private BiConsumer>, RemovalCause> removeListener = (removes, removalCause) -> { }; + private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); public LazyCache(int maximumSize, long expireAfterAccessMillis, long expireCheckIntervalMillis, BiConsumer>, RemovalCause> removeListener) { AssertionUtils.ge1(maximumSize); @@ -155,16 +156,23 @@ public class LazyCache { removeListener.accept(removeList, removalCause); } - private synchronized void checkMaximumSize() { - if (cacheMap.size() > backPressureSize) { - var removeList = cacheMap.values() - .stream() - .sorted((a, b) -> Long.compare(a.expireTime, b.expireTime)) - .limit(Math.max(0, cacheMap.size() - maximumSize)) - .toList(); - removeForCause(removeList, RemovalCause.SIZE); + private void checkMaximumSize() { + if (rwLock.writeLock().tryLock()) { // 获取写锁 + try { + if (cacheMap.size() > backPressureSize) { + var removeList = cacheMap.values() + .stream() + .sorted((a, b) -> Long.compare(a.expireTime, b.expireTime)) + .limit(Math.max(0, cacheMap.size() - maximumSize)) + .toList(); + removeForCause(removeList, RemovalCause.SIZE); + } + } finally { + rwLock.writeLock().unlock(); + } } } + synchronized private void checkExpire() { var now = TimeUtils.now();