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 da80698..43929c7 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/collection/SafeConcurrentHashMap.java @@ -22,9 +22,21 @@ import java.util.function.Function; import javax.annotation.concurrent.ThreadSafe; +import xyz.zhouxy.plusone.commons.base.JRE; import xyz.zhouxy.plusone.commons.util.ConcurrentHashMapUtil; -// TODO 添加文档注释 +/** + * SafeConcurrentHashMap + * + *

+ * Java 8 的 {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} 方法有 bug, + * 使用 Java 8 时,可使用这个类进行替换。 + * + * @author ZhouXY + * @since 1.0 + * @see ConcurrentHashMap + * @see ConcurrentHashMapUtil#computeIfAbsentForJava8(ConcurrentHashMap, Object, Function) + */ @ThreadSafe public class SafeConcurrentHashMap extends ConcurrentHashMap { @@ -102,6 +114,8 @@ public class SafeConcurrentHashMap extends ConcurrentHashMap { /** {@inheritDoc} */ @Override public V computeIfAbsent(K key, Function mappingFunction) { - return ConcurrentHashMapUtil.computeIfAbsentForJava8(this, key, mappingFunction); + return JRE.isJava8() + ? ConcurrentHashMapUtil.computeIfAbsentForJava8(this, key, mappingFunction) + : super.computeIfAbsent(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 30d48c5..2d870a4 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/util/ConcurrentHashMapUtil.java @@ -21,12 +21,28 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import xyz.zhouxy.plusone.commons.base.JRE; +import xyz.zhouxy.plusone.commons.collection.SafeConcurrentHashMap; -public class ConcurrentHashMapUtil { // TODO 添加文档注释 +/** + * ConcurrentHashMapUtil + * + *

+ * Java 8 的 {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} 方法有 bug, + * 可使用这个工具类的 {@link computeIfAbsentForJava8} 进行替换。 + * + *

+ * NOTE: 方法来自Dubbo,见:issues#2349 + * + * @author ZhouXY + * @since 1.0 + * @see ConcurrentHashMap + * @see SafeConcurrentHashMap + */ +public class ConcurrentHashMapUtil { public static V computeIfAbsent(ConcurrentHashMap map, final K key, final Function mappingFunction) { - + Objects.requireNonNull(map, "map"); return JRE.isJava8() ? computeIfAbsentForJava8(map, key, mappingFunction) : map.computeIfAbsent(key, mappingFunction); @@ -34,6 +50,7 @@ public class ConcurrentHashMapUtil { // TODO 添加文档注释 public static V computeIfAbsentForJava8(ConcurrentHashMap map, final K key, final Function mappingFunction) { + Objects.requireNonNull(key); Objects.requireNonNull(mappingFunction); V v = map.get(key); if (null == v) {