zjf*_*fdu 16 java concurrency java.util.concurrent
我想要一个与BlockingQueue非常相似的BlockingMap数据结构.BlockingQueue的take方法将在那里等待,直到元素可用.我希望BlockingMap的get方法在那里等待,直到相应的密钥可用?我可以使用这种数据结构吗?
小智 9
这是一个使用 BlockingQueue 和 ConcurrentHashMap 的极其简单的实现:
public class BlockingMap<K, V> {
private Map<K, ArrayBlockingQueue<V>> map = new ConcurrentHashMap<>();
private BlockingQueue<V> getQueue(K key, boolean replace) {
return map.compute(key, (k, v) -> replace || v == null ? new ArrayBlockingQueue<>(1) : v);
}
public void put(K key, V value) {
getQueue(key, true).add(value);
}
public V get(K key) throws InterruptedException {
return getQueue(key, false).take();
}
public V get(K key, long timeout, TimeUnit unit) throws InterruptedException {
return getQueue(key, false).poll(timeout, unit);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9912 次 |
| 最近记录: |