Is there BlockingMap as BlockingQueue in java?

微笑、不失礼 提交于 2019-11-29 11:32:09

问题


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 ?


回答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.




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/20945984/is-there-blockingmap-as-blockingqueue-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!