本文介绍了是否存在带有getAndWait()方法的HashMap?例如。一个BlockingConcurrentHashMap实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
许多线程可能会填充 HashMap
,在某些情况下我需要等待(阻塞)直到HashMap中存在一个对象,例如:
Many threads may populate a HashMap
, in some cases I need to wait (block) until an object exists in the HashMap, such as:
BlockingConcurrentHashMap map = new BlockingConcurrentHashMap();
Object x = map.getAndWait(key, 1000); //(object_to_get, max_delay_ms)
想知道这样的东西是否存在,我讨厌重新发明轮子。
Wondering if such a thing exists already, I hate re-inventing wheels.
推荐答案
据我所知,没有转移地图可用。虽然在理论上创建一个并不太困难。
As far as I know, there is no 'Transfer Map' available. Though the creation of one in theory isn't too difficult.
public class TransferMap<K,V> implements Map<K,V>{
@GuardedBy("lock")
private final HashMap<K,V> backingMap = new HashMap<K,V>();
private final Object lock = new Object();
public V getAndWait(Object key){
synchronized(lock){
V value = null;
do{
value = backingMap.get(key);
if(value == null) lock.wait();
}while(value == null);
}
return value;
}
public V put(K key, V value){
synchronized(lock){
V value = backingMap.put(key,value);
lock.notifyAll();
}
return value;
}
}
此课程中有明显的排除。没有提到锁粗化;不用说它不会表现出色,但你应该知道发生了什么
There are obvious exclusions in this class. Not to mentioned the lock coarsening; needless to say it won't perform great, but you should get the idea of what is going on
这篇关于是否存在带有getAndWait()方法的HashMap?例如。一个BlockingConcurrentHashMap实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!