private static <KEY, VALUE, C extends Collection<VALUE>> void removeFromMapValueCollection(
      ConcurrentMap<KEY, C> map, KEY key, VALUE value,
      CollectionFactory<VALUE, C> factory) {

    while (true) {

      C values = map.get(key);

      if (values == null)
        return;

      C origCopy = factory.copy(values);

      if (!origCopy.contains(value))
        return;

      C reducedCopy = factory.copy(origCopy);
      reducedCopy.remove(value);

      if (reducedCopy.isEmpty()) {
        if (map.remove(key, origCopy))
          return;
      } else {
        if (map.replace(key, origCopy, reducedCopy))
          return;
      }
    }
  }