我有多线程通信。 1 线程正在向其他线程分派(dispatch)数据。
主线程正在推送数据:
主线程: ConcurrentHashMap map = Global.getInstance().getMap(); //将数据推送到其他线程 map.put(1,"测试");
线程 1: 字符串数据 = map.get(1); //直接返回null,但我想等到数据推送
如果主线程没有推送任何数据,线程 1 返回 null。 但我想等到我得到数据, 我怎么等?
TransferQueue 不是我当前实现的好的解决方案。 我必须处理 ConcurrentHashMap。
有人知道解决办法吗?
最佳答案
你可以创建一个 BlockingMap,像这样;根据使用情况,您还应该设置一种机制来删除未使用的键和与其关联的队列,以避免内存泄漏。
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 开始,ensureQueueExists
可以这样写:
private synchronized BlockingQueue<V> ensureQueueExists(K key) {
return map.computeIfAbsent(key, k -> new ArrayBlockingQueue<>(1));
}
关于java - ConcurrentHashMap 等待键可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23917818/