我有一個要求,我必須有一個Map<Comparable, Set<Comparable>>
,其中地圖上的插入是併發的,並且也在相應的Set上,但是一旦Key從Map消耗完,它必須被刪除,認爲是Job每兩秒鐘是從一個特定的重點,但插入消耗整個Set<Comparable>
運行完全同步,這樣,當作業踢,這裏最值緩衝是我實現:
注:我用番石榴的輔助類地圖創建併發映射,此解決方案也可模擬實踐中的Java併發性列表5.19:
import com.google.common.collect.MapMaker;
import java.util.concurrent.ConcurrentMap;
/**
* Created by IntelliJ IDEA.
* User: gmedina
* Date: 18-Sep-2012
* Time: 09:17:50
*/
public class LockMap<K extends Comparable>
{
private final ConcurrentMap<K, Object> locks;
public LockMap()
{
this(16, 64);
}
public LockMap(final int concurrencyLevel)
{
this(concurrencyLevel, 64);
}
public LockMap(final int concurrencyLevel, final int initialCapacity)
{
locks=new MapMaker().concurrencyLevel(concurrencyLevel).initialCapacity(initialCapacity).weakValues().makeMap();
}
public Object getLock(final K key)
{
final Object object=new Object();
Object lock=locks.putIfAbsent(key, object);
return lock == null ? object : lock;
}
}
import com.google.common.collect.MapMaker;
import com.google.common.collect.Sets;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
/**
* A general purpose Multimap implementation for delayed processing and concurrent insertion/deletes.
*
* @param <K> A comparable Key
* @param <V> A comparable Value
*/
public class ConcurrentMultiMap<K extends Comparable, V extends Comparable>
{
private final int initialCapacity;
private final LockMap<K> locks;
private final ConcurrentMap<K, Set<V>> cache;
public ConcurrentMultiMap()
{
this(16, 64);
}
public ConcurrentMultiMap(final int concurrencyLevel)
{
this(concurrencyLevel, 64);
}
public ConcurrentMultiMap(final int concurrencyLevel, final int initialCapacity)
{
this.initialCapacity=initialCapacity;
cache=new MapMaker().concurrencyLevel(concurrencyLevel).initialCapacity(initialCapacity).makeMap();
locks=new LockMap<K>(concurrencyLevel, initialCapacity);
}
public void put(final K key, final V value)
{
synchronized(locks.getLock(key)){
Set<V> set=cache.get(key);
if(set == null){
set=Sets.newHashSetWithExpectedSize(initialCapacity);
cache.put(key, set);
}
set.add(value);
}
}
public void putAll(final K key, final Collection<V> values)
{
synchronized(locks.getLock(key)){
Set<V> set=cache.get(key);
if(set == null){
set=Sets.newHashSetWithExpectedSize(initialCapacity);
cache.put(key, set);
}
set.addAll(values);
}
}
public Set<V> remove(final K key)
{
synchronized(locks.getLock(key)){
return cache.remove(key);
}
}
public Set<K> getKeySet()
{
return cache.keySet();
}
public int size()
{
return cache.size();
}
}
我不確定性能數字,但似乎您可能能夠快速基準測試可用的不同實現?最常見的圖書館將是Apache和Google Guava圖書館的公共收藏。 – gpampara 2010-08-10 05:44:35