これはで構成され、同時リストマルチマップの実装です。下位レベルの実装はより優れていますが、より複雑になります。並行マルチマップの配置と削除
サブリストのO(n)削除を無視すると、ConcurrentMapとCopyOnWriteArrayListを機能的なConcurrentMultimapに構成する正しい方法ですか?未解決のデータ競合はありますか?
private final ConcurrentMap<K, Collection<V>> map = ...; // inconsequential
public boolean put(K key, V value) {
Collection<V> list = map.get(key);
if(list != null) {
list.add(value);
return true;
}
// put if absent double check to avoid extra list creation
list = new CopyOnWriteArrayList<V>();
list.add(value);
Collection<V> old = map.putIfAbsent(key,value);
if(old != null) old.add(value);
return true;
}
public boolean remove(Object key, Object value) {
Collection<V> list = map.get(key);
if(list == null) return false;
// O(n) remove is the least of my worries
if(! list.remove(value)) return false;
if(! list.isEmpty()) return true;
// double-check remove
if(! map.remove(key,list)) return true; // already removed! (yikes)
if(list.isEmpty()) return true;
// another entry was added!
Collection<V> old = map.putIfAbsent(key,list);
if(old == null) return true;
// new list added!
old.addAll(list);
return true;
}
もちろん私はlist.remove(value)のboolean結果をチェックしませんでした!いつも最も簡単なこと... –
私は、起こる前のルールが正しい動作を保証できる原則を開発していると思います。 –