001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.util; 019 020import java.io.IOException; 021import java.util.concurrent.ConcurrentMap; 022import java.util.function.Supplier; 023import org.apache.yetus.audience.InterfaceAudience; 024 025/** 026 * Utility methods for dealing with Collections, including treating null collections as empty. 027 */ 028@InterfaceAudience.Private 029public class ConcurrentMapUtils { 030 031 /** 032 * In HBASE-16648 we found that ConcurrentHashMap.get is much faster than computeIfAbsent if the 033 * value already exists. Notice that the implementation does not guarantee that the supplier will 034 * only be executed once. 035 */ 036 public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Supplier<V> supplier) { 037 return computeIfAbsent(map, key, supplier, () -> { 038 }); 039 } 040 041 /** 042 * In HBASE-16648 we found that ConcurrentHashMap.get is much faster than computeIfAbsent if the 043 * value already exists. So here we copy the implementation of 044 * {@link ConcurrentMap#computeIfAbsent(Object, java.util.function.Function)}. It uses get and 045 * putIfAbsent to implement computeIfAbsent. And notice that the implementation does not guarantee 046 * that the supplier will only be executed once. 047 */ 048 public static <K, V> V computeIfAbsentEx(ConcurrentMap<K, V> map, K key, 049 IOExceptionSupplier<V> supplier) throws IOException { 050 V v, newValue; 051 return ((v = map.get(key)) == null && (newValue = supplier.get()) != null 052 && (v = map.putIfAbsent(key, newValue)) == null) ? newValue : v; 053 } 054 055 public static <K, V> V computeIfAbsent(ConcurrentMap<K, V> map, K key, Supplier<V> supplier, 056 Runnable actionIfAbsent) { 057 V v = map.get(key); 058 if (v != null) { 059 return v; 060 } 061 V newValue = supplier.get(); 062 v = map.putIfAbsent(key, newValue); 063 if (v != null) { 064 return v; 065 } 066 actionIfAbsent.run(); 067 return newValue; 068 } 069}