Java tutorial
/** * Copyright 2012 Julien Eluard * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * 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.github.jeluard.guayaba.util.concurrent; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import java.util.concurrent.ConcurrentMap; /** * Helper methods for {@link ConcurrentMap}s. */ public final class ConcurrentMaps { private ConcurrentMaps() { } /** * Returns value associated with key if exists. * Otherwise create value using provided {@link Supplier}, insert it map then returns it. * * TODO improve based on http://blog.boundary.com/2011/05/ * * @param <K> * @param <V> * @param concurrentMap * @param key * @param supplier * @return previous value if exists; result of {@link Supplier#get()} otherwise */ public static synchronized <K, V> V putIfAbsentAndReturn(final ConcurrentMap<K, V> concurrentMap, final K key, final Supplier<V> supplier) { Preconditions.checkNotNull(concurrentMap, "null concurrentMap"); Preconditions.checkNotNull(key, "null key"); Preconditions.checkNotNull(supplier, "null supplier"); if (concurrentMap.containsKey(key)) { return concurrentMap.get(key); } final V value = supplier.get(); concurrentMap.put(key, value); return value; } }