From bb810d2d648a42eded7b0462c03796f8a4f335d2 Mon Sep 17 00:00:00 2001 From: winlans Date: Fri, 28 Feb 2025 12:03:40 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=B7=B2=E8=BF=87=E6=9C=9Fkey=EF=BC=8Co?= =?UTF-8?q?nRemove=E5=81=B6=E5=B0=94=E8=A7=A6=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/hutool/cache/impl/ReentrantCache.java | 1 + .../test/java/cn/hutool/cache/CacheTest.java | 29 ++++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/hutool-cache/src/main/java/cn/hutool/cache/impl/ReentrantCache.java b/hutool-cache/src/main/java/cn/hutool/cache/impl/ReentrantCache.java index 8974c4d12..51e044b1c 100755 --- a/hutool-cache/src/main/java/cn/hutool/cache/impl/ReentrantCache.java +++ b/hutool-cache/src/main/java/cn/hutool/cache/impl/ReentrantCache.java @@ -112,6 +112,7 @@ public abstract class ReentrantCache extends AbstractCache { if(null != co && co.isExpired()){ //过期移除 removeWithoutLock(key); + onRemove(co.key, co.obj); co = null; } } finally { diff --git a/hutool-cache/src/test/java/cn/hutool/cache/CacheTest.java b/hutool-cache/src/test/java/cn/hutool/cache/CacheTest.java index 62766f779..39a39241c 100755 --- a/hutool-cache/src/test/java/cn/hutool/cache/CacheTest.java +++ b/hutool-cache/src/test/java/cn/hutool/cache/CacheTest.java @@ -4,13 +4,17 @@ import cn.hutool.cache.impl.TimedCache; import cn.hutool.core.date.DateUnit; import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.util.RandomUtil; + import static org.junit.jupiter.api.Assertions.*; + import org.junit.jupiter.api.Test; +import java.util.concurrent.atomic.AtomicInteger; + /** * 缓存测试用例 - * @author Looly * + * @author Looly */ public class CacheTest { @@ -121,4 +125,27 @@ public class CacheTest { //取消定时清理 timedCache.cancelPruneSchedule(); } + + + /** + * TimedCache的数据过期后不是每次都触发监听器onRemove,而是偶尔触发onRemove + * https://gitee.com/chinabugotech/hutool/issues/IBP752 + */ + @Test + public void whenContainsKeyTimeout_shouldCallOnRemove() { + int timeout = 50; + final TimedCache ALARM_CACHE = new TimedCache<>(timeout); + + AtomicInteger counter = new AtomicInteger(0); + ALARM_CACHE.setListener((key, value) -> { + counter.incrementAndGet(); + }); + + ALARM_CACHE.put(1, "value1"); + + ThreadUtil.sleep(100); + + assertFalse(ALARM_CACHE.containsKey(1)); + assertEquals(1, counter.get()); + } }