001/*
002 *  Copyright (c) 2022-2023, Mybatis-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.mybatisflex.core.util;
017
018import java.util.AbstractMap;
019import java.util.Map;
020import java.util.function.Function;
021
022public class MapUtil {
023    private static final boolean IS_JDK8 = (8 == getJvmVersion0());
024
025    private MapUtil() {
026    }
027
028    private static int getJvmVersion0() {
029        int jvmVersion = -1;
030        try {
031            String javaSpecVer = StringUtil.tryTrim(System.getProperty("java.specification.version"));
032            if (StringUtil.isNotBlank(javaSpecVer)) {
033                if (javaSpecVer.startsWith("1.")) {
034                    javaSpecVer = javaSpecVer.substring(2);
035                }
036                if (javaSpecVer.indexOf('.') == -1) {
037                    jvmVersion = Integer.parseInt(javaSpecVer);
038                }
039            }
040        } catch (Throwable ignore) {
041            // ignore
042        }
043        // default is jdk8
044        if (jvmVersion == -1) {
045            jvmVersion = 8;
046        }
047        return jvmVersion;
048    }
049
050    /**
051     * A temporary workaround for Java 8 specific performance issue JDK-8161372 .<br>
052     * This class should be removed once we drop Java 8 support.
053     *
054     * @see <a href=
055     * "https://bugs.openjdk.java.net/browse/JDK-8161372">https://bugs.openjdk.java.net/browse/JDK-8161372</a>
056     */
057    public static <K, V> V computeIfAbsent(Map<K, V> map, K key, Function<K, V> mappingFunction) {
058        if (IS_JDK8) {
059            V value = map.get(key);
060            if (value != null) {
061                return value;
062            }
063        }
064        return map.computeIfAbsent(key, mappingFunction);
065    }
066
067
068    public static <K, V> Map.Entry<K, V> entry(K key, V value) {
069        return new AbstractMap.SimpleImmutableEntry<>(key, value);
070    }
071
072
073}