Java ConcurrentMap removeFromContainedSet(ConcurrentMap> map, K mapKey, V value)

Here you can find the source of removeFromContainedSet(ConcurrentMap> map, K mapKey, V value)

Description

remove From Contained Set

License

Open Source License

Declaration

public static <K, V> boolean removeFromContainedSet(ConcurrentMap<K, Set<V>> map, K mapKey, V value) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class Main {
    public static <K, V> boolean removeFromContainedSet(ConcurrentMap<K, Set<V>> map, K mapKey, V value) {
        Set<V> existingSet = map.get(mapKey);
        if (existingSet == null) {
            // It might look like checking for null and then creating something means that we need a lock.
            // this isn't the case, as the ACTUAL point of synchronization is the map.putIfAbsent() below.
            // it's perfectly possible to have multiple threads enter this block at the same time.
            // this is fine, as the only "true" value added is added by the putIfAbsent() call.
            // this race will only be an issue in the beginning. Once putIfAbsent() has succeeded,
            // the outer if-statement will always be false, which means we can avoid creating the
            // inner container and calling putIfAbsent() again.
            // This replaces this more legible but slower pattern:
            // map.putIfAbsent(mapKey, Collections.newSetFromMap(new ConcurrentHashMap<V, Boolean>())); // ensure that we have something
            // map.get(mapKey).add(value);
            // See slides 54 and 55 of this presentation regarding the speed of this: http://www.slideshare.net/marakana/effective-java-still-effective-after-all-these-years
            Set<V> newSet = Collections.newSetFromMap(new ConcurrentHashMap<>());
            existingSet = map.putIfAbsent(mapKey, newSet);
            if (existingSet == null) {
                // we've added a new set
                existingSet = newSet;/*from  ww  w . j  a va2 s .  c  om*/
            }
        }
        return existingSet.remove(value);
    }
}

Related

  1. putIfAbsent(ConcurrentMap target, K key, V value)
  2. putIfAbsent(final ConcurrentMap map, final K key, final V value)
  3. putIfAbsentAndGet(ConcurrentMap map, K key, V newValue)
  4. remove(ConcurrentMap map, K key, V value)
  5. remove(K key, ConcurrentMap map, Object value)