Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 951
zjffdu Avatar asked Jan 06 '14 08:01

zjffdu


People also ask

What is the max capacity of a Java BlockingQueue?

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.

What is a BlockingQueue in Java?

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.

Is Java BlockingQueue thread-safe?

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

Is BlockingQueue synchronized?

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.


2 Answers

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.

like image 83
Chthonic Project Avatar answered Sep 24 '22 06:09

Chthonic Project


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);     } } 
like image 21
Ofri Mann Avatar answered Sep 20 '22 06:09

Ofri Mann