Is there BlockingMap as BlockingQueue in java?
Here is an extremely simple implementation using BlockingQueue and ConcurrentHashMap:
public class BlockingMap<K, V> {
private Map<K, ArrayBlockingQueue<V>> map = new ConcurrentHashMap<>();
private BlockingQueue<V> getQueue(K key) {
return map.computeIfAbsent(key, k -> new ArrayBlockingQueue<>(1));
}
public void put(K key, V value) {
// can also use add(value) if you want an exception thrown
if ( !getQueue(key).offer(value) ) {
System.err.println("Ignoring duplicate key");
}
}
public V get(K key) throws InterruptedException {
return getQueue(key).take();
}
public V get(K key, long timeout, TimeUnit unit) throws InterruptedException {
return getQueue(key).poll(timeout, unit);
}
}
I have simply used BlockingQueue<Map.Entry<K,V>>
in the past. But recently, I came across this Blocking Map for Java. Haven't used it myself, though.