ConcurrentHashMap等待密钥可能吗? [英] ConcurrentHashMap wait for key possible?
问题描述
我有多线程通信。
1线程正在将数据分发到其他线程。
i have multithread communication. 1 Thread is dispatching datas to other threads.
主线程正在推送数据:
Main线程:
ConcurrentHashMap map = Global.getInstance()。getMap();
//将数据推送到其他线程
map.put(1, Test);
Main Thread: ConcurrentHashMap map = Global.getInstance().getMap(); //push data to some other thread map.put(1,"Test");
线程1:
字符串数据= map.get(1);
//直接返回null,但是我要等到推送数据
Thread 1: String data = map.get(1); //returns null directly , but i want to wait until data pushed
如果主线程不推送任何数据,线程1返回null。
但是我要等到获得数据后,才能等待
呢?
Thread 1 returns null if main thread doesn't push any data. But i want to wait until i got data , how can i wait ?
TransferQueue对于我当前的实现不是一个好的解决方案。
我和ConcurrentHashMap有关。
TransferQueue is not good solution to my current implementation. I have to do with ConcurrentHashMap.
有人知道任何解决方案吗?
Does someone know any solution?
推荐答案
您可以创建一个BlockingMap,如下所示:根据使用情况,还应该使用一种机制来删除未使用的键和与其关联的队列,以避免内存泄漏。
You can create a BlockingMap, something like this; depending on usage, you should also device a mechanism to remove unused keys and queues associated to them in order to avoid a memory leak.
public class BlockingMap<K, V> {
private final Map<K, BlockingQueue<V>> map = new ConcurrentHashMap<>();
private synchronized BlockingQueue<V> ensureQueueExists(K key) {
//concurrentMap.putIfAbsent would require creating a new
//blocking queue each time put or get is called
if (map.containsKey(key)) {
return map.get(key);
} else {
BlockingQueue<V> queue = new ArrayBlockingQueue<>(1);
map.put(key, queue);
return queue;
}
}
public boolean put(K key, V value, long timeout, TimeUnit timeUnit) {
BlockingQueue<V> queue = ensureQueueExists(key);
try {
return queue.offer(value, timeout, timeUnit);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
public V get(K key, long timeout, TimeUnit timeUnit) {
BlockingQueue<V> queue = ensureQueueExists(key);
try {
return queue.poll(timeout, timeUnit);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
自Java 8起,<$可以将c $ c> ensureQueueExists 编写为:
Since Java 8, ensureQueueExists
can be written:
private synchronized BlockingQueue<V> ensureQueueExists(K key) {
return map.computeIfAbsent(key, k -> new ArrayBlockingQueue<>(1));
}
这篇关于ConcurrentHashMap等待密钥可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!