Java ConcurrentMap putIfAbsentAndGet(ConcurrentMap map, K key, V newValue)

Here you can find the source of putIfAbsentAndGet(ConcurrentMap map, K key, V newValue)

Description

If the specified key is not already associated with a value, associate it with the given value.

License

Open Source License

Declaration

public static <K, V> V putIfAbsentAndGet(ConcurrentMap<K, V> map, K key, V newValue) 

Method Source Code


//package com.java2s;

import java.util.concurrent.ConcurrentMap;

public class Main {
    /**//  ww  w  .  j a  va 2  s .c om
     * If the specified key is not already associated
     * with a value, associate it with the given value.
     * And return the final value stored in the map.
     *
     * This is equivalent to
     * <pre> {@code
     * if (!map.containsKey(key)) {
     *   map.put(key, value);
     *   return value;
     * } else {
     *   return map.get(key);
     * }}</pre>
     *
     * except that the action is performed atomically.
     */
    public static <K, V> V putIfAbsentAndGet(ConcurrentMap<K, V> map, K key, V newValue) {
        final V old = map.putIfAbsent(key, newValue);
        return old != null ? old : newValue;
    }
}

Related

  1. putIfAbsent(ConcurrentMap map, K key, V value)
  2. putIfAbsent(ConcurrentMap map, K key, V value)
  3. putIfAbsent(ConcurrentMap map, K key, V value)
  4. putIfAbsent(ConcurrentMap target, K key, V value)
  5. putIfAbsent(final ConcurrentMap map, final K key, final V value)
  6. remove(ConcurrentMap map, K key, V value)
  7. remove(K key, ConcurrentMap map, Object value)
  8. removeFromContainedSet(ConcurrentMap> map, K mapKey, V value)