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 ?
Here we have a blockingQueue that has a capacity equal to 10. It means that when a producer tries to add an element to an already full queue, depending on a method that was used to add it (offer(), add() or put()), it will block until space for inserting object becomes available. Otherwise, the operations will fail.
BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.
No, you do not need to synchronize access to the object properties, or even use volatile on the member variables. All actions performed by a thread before it queues an object on a BlockingQueue "happen-before" the object is dequeued. That means that any changes made by the first thread are visible to the second.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With