'Is there BlockingMap as BlockingQueue in java?

I'd like to have one BlockingMap data structure which is very similar to BlockingQueue. The take method of BlockingQueue will wait there until element is available. I'd like the get method of BlockingMap to wait there until the corresponding key is available? Is this kind of data structure available that I can use ?



Solution 1:[1]

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.

Solution 2:[2]

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);
    }
}

Solution 3:[3]

I hope this is what you want.

public class BlockingHashMap<K,V>
extends java.lang.Object
implements BlockingMap<K,V>

get

public V get(java.lang.Object key)

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. Note that null is used as a special marker to indicate the absence of the requested key

Specified by:

get in interface java.util.Map<K,V>

Specified by:

get in interface BlockingMap<K,V>

Parameters:

key - the key whose associated value is to be returned

Returns:

the value to which the specified key is mapped, or null if this map contains no mapping for the key

Throws:

java.lang.ClassCastException - if the key is of an inappropriate type for this map
java.lang.NullPointerException - if the specified key is null and this map does not permit null keys (optional)
java.lang.IllegalStateException - if the map has been shut-down

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chthonic Project
Solution 2
Solution 3 Reuben