diff --git a/agents-flex-core/src/main/java/com/agentsflex/core/util/MapUtil.java b/agents-flex-core/src/main/java/com/agentsflex/core/util/MapUtil.java new file mode 100644 index 0000000..e250e3d --- /dev/null +++ b/agents-flex-core/src/main/java/com/agentsflex/core/util/MapUtil.java @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2023-2025, Agents-Flex (fuhai999@gmail.com). + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.agentsflex.core.util; + +import java.util.Map; +import java.util.function.Function; + +public class MapUtil { + private static final boolean IS_JDK8 = (8 == getJvmVersion0()); + + private MapUtil() { + } + + private static String tryTrim(String string) { + return string != null ? string.trim() : ""; + } + + private static int getJvmVersion0() { + int jvmVersion = -1; + try { + String javaSpecVer = tryTrim(System.getProperty("java.specification.version")); + if (StringUtil.hasText(javaSpecVer)) { + if (javaSpecVer.startsWith("1.")) { + javaSpecVer = javaSpecVer.substring(2); + } + if (javaSpecVer.indexOf('.') == -1) { + jvmVersion = Integer.parseInt(javaSpecVer); + } + } + } catch (Throwable ignore) { + // ignore + } + // default is jdk8 + if (jvmVersion == -1) { + jvmVersion = 8; + } + return jvmVersion; + } + + /** + * A temporary workaround for Java 8 specific performance issue JDK-8161372 .
+ * This class should be removed once we drop Java 8 support. + * + * @see https://bugs.openjdk.java.net/browse/JDK-8161372 + */ + public static V computeIfAbsent(Map map, K key, Function mappingFunction) { + if (IS_JDK8) { + V value = map.get(key); + if (value != null) { + return value; + } + } + return map.computeIfAbsent(key, mappingFunction); + } + +}