From 2d40dd192766494551f345871799ea5281c72a4a Mon Sep 17 00:00:00 2001 From: Looly Date: Tue, 18 Jun 2024 11:34:46 +0800 Subject: [PATCH] =?UTF-8?q?Cache.put=E5=8F=98=E6=9B=B4=E7=AD=96=E7=95=A5?= =?UTF-8?q?=EF=BC=8C=E5=AF=B9=E4=BA=8E=E6=9B=BF=E6=8D=A2=E7=9A=84=E9=94=AE?= =?UTF-8?q?=E5=80=BC=E5=AF=B9=EF=BC=8C=E4=B8=8D=E6=B8=85=E7=90=86=E9=98=9F?= =?UTF-8?q?=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 3 ++- .../cn/hutool/cache/impl/AbstractCache.java | 12 +++++++++- .../java/cn/hutool/cache/Issue3618Test.java | 22 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 hutool-cache/src/test/java/cn/hutool/cache/Issue3618Test.java diff --git a/CHANGELOG.md b/CHANGELOG.md index e43a252bd..16af7fe7c 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ # 🚀Changelog ------------------------------------------------------------------------------------------------------------- -# 5.8.29(2024-06-17) +# 5.8.29(2024-06-18) ### 🐣新特性 * 【core 】 DateUtil增加offsetYear方法 @@ -11,6 +11,7 @@ * 【core 】 优化DateUtil.format(Date date, String format)接口效率(pr#1226@Gitee) * 【csv 】 CsvWriter.writeBeans增加重载,可选是否写出表头(issue#IA57W2@Gitee) * 【core 】 BetweenFormatter支持自定义设置单位(pr#1228@Gitee) +* 【cache 】 Cache.put变更策略,对于替换的键值对,不清理队列(issue#3618@Github) ### 🐞Bug修复 * 【core 】 修复AnnotationUtil可能的空指针错误 diff --git a/hutool-cache/src/main/java/cn/hutool/cache/impl/AbstractCache.java b/hutool-cache/src/main/java/cn/hutool/cache/impl/AbstractCache.java index 56f4675e2..c4a4d9bdd 100755 --- a/hutool-cache/src/main/java/cn/hutool/cache/impl/AbstractCache.java +++ b/hutool-cache/src/main/java/cn/hutool/cache/impl/AbstractCache.java @@ -85,10 +85,20 @@ public abstract class AbstractCache implements Cache { if (timeout != 0) { existCustomTimeout = true; } + + final MutableObj mKey = MutableObj.of(key); + + // issue#3618 对于替换的键值对,不做满队列检查和清除 + if (cacheMap.containsKey(mKey)) { + // 存在相同key,覆盖之 + cacheMap.put(mKey, co); + return; + } + if (isFull()) { pruneCache(); } - cacheMap.put(MutableObj.of(key), co); + cacheMap.put(mKey, co); } // ---------------------------------------------------------------- put end diff --git a/hutool-cache/src/test/java/cn/hutool/cache/Issue3618Test.java b/hutool-cache/src/test/java/cn/hutool/cache/Issue3618Test.java new file mode 100644 index 000000000..d914091c2 --- /dev/null +++ b/hutool-cache/src/test/java/cn/hutool/cache/Issue3618Test.java @@ -0,0 +1,22 @@ +package cn.hutool.cache; + +import cn.hutool.cache.impl.FIFOCache; +import org.junit.Assert; +import org.junit.Test; + +public class Issue3618Test { + @Test + public void putTest() { + FIFOCache cache = CacheUtil.newFIFOCache(3); + cache.put(1, 1); + cache.put(2, 1); + cache.put(3, 1); + + Assert.assertEquals(3, cache.size()); + + // issue#3618 对于替换的键值对,不做满队列检查和清除 + cache.put(3, 2); + + Assert.assertEquals(3, cache.size()); + } +}