From b178be9a6f7cbd322b42bdb9bcfae3494bf17408 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Sat, 9 Sep 2023 13:54:14 +0800 Subject: [PATCH] Fix bug. --- .../collection/SafeConcurrentHashMap.java | 2 +- .../commons/util/ConcurrentHashMapUtil.java | 35 +++++++++++-------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java b/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java index 4a351be..da80698 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java @@ -102,6 +102,6 @@ public class SafeConcurrentHashMap extends ConcurrentHashMap { /** {@inheritDoc} */ @Override public V computeIfAbsent(K key, Function mappingFunction) { - return ConcurrentHashMapUtil.computeIfAbsent(this, key, mappingFunction); + return ConcurrentHashMapUtil.computeIfAbsentForJava8(this, key, mappingFunction); } } diff --git a/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java b/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java index b913f3a..30d48c5 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java @@ -24,24 +24,29 @@ import xyz.zhouxy.plusone.commons.base.JRE; public class ConcurrentHashMapUtil { // TODO 添加文档注释 - public static V computeIfAbsent(ConcurrentHashMap map, final K key, final Function mappingFunction) { - if (JRE.isJava8()) { - Objects.requireNonNull(mappingFunction); - V v = map.get(key); + public static V computeIfAbsent(ConcurrentHashMap map, final K key, + final Function mappingFunction) { + + return JRE.isJava8() + ? computeIfAbsentForJava8(map, key, mappingFunction) + : map.computeIfAbsent(key, mappingFunction); + } + + public static V computeIfAbsentForJava8(ConcurrentHashMap map, final K key, + final Function mappingFunction) { + Objects.requireNonNull(mappingFunction); + V v = map.get(key); + if (null == v) { + v = mappingFunction.apply(key); if (null == v) { - v = mappingFunction.apply(key); - if (null == v) { - return null; - } - final V res = map.putIfAbsent(key, v); - if (null != res) { - return res; - } + return null; + } + final V res = map.putIfAbsent(key, v); + if (null != res) { + return res; } - return v; - } else { - return map.computeIfAbsent(key, mappingFunction); } + return v; } private ConcurrentHashMapUtil() {