001/*
002 *  Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com).
003 *  <p>
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *  <p>
008 *  http://www.apache.org/licenses/LICENSE-2.0
009 *  <p>
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package com.agentsflex.core.util;
017
018import java.util.Map;
019import java.util.function.Function;
020
021public class MapUtil {
022    private static final boolean IS_JDK8 = (8 == getJvmVersion0());
023
024    private MapUtil() {
025    }
026
027    private static String tryTrim(String string) {
028        return string != null ? string.trim() : "";
029    }
030
031    private static int getJvmVersion0() {
032        int jvmVersion = -1;
033        try {
034            String javaSpecVer = tryTrim(System.getProperty("java.specification.version"));
035            if (StringUtil.hasText(javaSpecVer)) {
036                if (javaSpecVer.startsWith("1.")) {
037                    javaSpecVer = javaSpecVer.substring(2);
038                }
039                if (javaSpecVer.indexOf('.') == -1) {
040                    jvmVersion = Integer.parseInt(javaSpecVer);
041                }
042            }
043        } catch (Throwable ignore) {
044            // ignore
045        }
046        // default is jdk8
047        if (jvmVersion == -1) {
048            jvmVersion = 8;
049        }
050        return jvmVersion;
051    }
052
053    /**
054     * A temporary workaround for Java 8 specific performance issue JDK-8161372 .<br>
055     * This class should be removed once we drop Java 8 support.
056     *
057     * @see <a href=
058     * "https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a>
059     */
060    public static <K, V> V computeIfAbsent(Map<K, V> map, K key, Function<K, V> mappingFunction) {
061        if (IS_JDK8) {
062            V value = map.get(key);
063            if (value != null) {
064                return value;
065            }
066        }
067        return map.computeIfAbsent(key, mappingFunction);
068    }
069
070}