From 4dd0ed53d566e795703eecd778cc9b36fde86806 Mon Sep 17 00:00:00 2001 From: Looly Date: Sun, 2 Apr 2023 19:09:22 +0800 Subject: [PATCH] fix code --- .../main/java/cn/hutool/core/map/MapUtil.java | 29 ++++++++++--------- .../core/map/SafeConcurrentHashMap.java | 11 +------ 2 files changed, 16 insertions(+), 24 deletions(-) diff --git a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java b/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java index b83133fab..eb40c708b 100755 --- a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java @@ -20,7 +20,6 @@ import cn.hutool.core.collection.iter.IterUtil; import cn.hutool.core.exceptions.UtilException; import cn.hutool.core.reflect.ConstructorUtil; import cn.hutool.core.text.StrUtil; -import cn.hutool.core.util.JdkUtil; import cn.hutool.core.util.ObjUtil; import java.util.*; @@ -1281,20 +1280,22 @@ public class MapUtil extends MapGetUtil { * @return 值 * @see https://bugs.openjdk.java.net/browse/JDK-8161372 */ - public static V computeIfAbsent(final Map map, final K key, final Function mappingFunction) { - if (JdkUtil.IS_JDK8) { - V value = map.get(key); - if (null == value) { - map.putIfAbsent(key, mappingFunction.apply(key)); - value = map.get(key); - - // 判空后调用依旧无法解决死循环问题 - // 见:Issue2349Test - //value = map.computeIfAbsent(key, mappingFunction); + public static V computeIfAbsentForJdk8(final Map map, final K key, final Function mappingFunction) { + V value = map.get(key); + if (null == value) { + value = mappingFunction.apply(key); + final V res = map.putIfAbsent(key, mappingFunction.apply(key)); + if(null != res){ + // issues#I6RVMY + // 如果旧值存在,说明其他线程已经赋值成功,putIfAbsent没有执行,返回旧值 + return res; } - return value; - } else { - return map.computeIfAbsent(key, mappingFunction); + // 如果旧值不存在,说明赋值成功,返回当前值 + + // Dubbo的解决方式,判空后调用依旧无法解决死循环问题 + // 见:Issue2349Test + //value = map.computeIfAbsent(key, mappingFunction); } + return value; } } diff --git a/hutool-core/src/main/java/cn/hutool/core/map/SafeConcurrentHashMap.java b/hutool-core/src/main/java/cn/hutool/core/map/SafeConcurrentHashMap.java index 5333b22d8..2fe187d90 100644 --- a/hutool-core/src/main/java/cn/hutool/core/map/SafeConcurrentHashMap.java +++ b/hutool-core/src/main/java/cn/hutool/core/map/SafeConcurrentHashMap.java @@ -84,16 +84,7 @@ public class SafeConcurrentHashMap extends ConcurrentHashMap { @Override public V computeIfAbsent(final K key, final Function mappingFunction) { if (JdkUtil.IS_JDK8) { - V value = get(key); - if (null == value) { - putIfAbsent(key, mappingFunction.apply(key)); - value = get(key); - - // 判空后调用依旧无法解决死循环问题 - // 见:Issue2349Test - //value = map.computeIfAbsent(key, mappingFunction); - } - return value; + return MapUtil.computeIfAbsentForJdk8(this, key, mappingFunction); } else { return super.computeIfAbsent(key, mappingFunction); }