我有一个要求,我必须有一个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