Many threads may populate a HashMap
, in some cases I need to wait (block) until an object exists in the HashMap, such as:
BlockingConcurrentHashMap map = new BlockingConcurrentHashMap();
Object x = map.getAndWait(key, 1000); //(object_to_get, max_delay_ms)
Wondering if such a thing exists already, I hate re-inventing wheels.
Hashmap uses the array of Nodes(named as table), where Node has fields like the key, value (and much more). Here the Node is represented by class HashMapEntry. Basically, HashMap has an array where the key-value data is stored. It calculates the index in the array where the Node can be placed and it is placed there.
2) HashMap doesn't allow duplicate keys. But it can have duplicate values. 3) HashMap can have multiple null values and only one null key. 4) HashMap is not synchronized.
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.
HashMap extends an abstract class AbstractMap and implements Cloneable and Serializable interfaces.
You can populate your Hashtable
with java.util.concurrent.FutureTask<ObjReturned>
s at the start with all the tasks you need to compute. You then use a thread pool to start executing your FutureTask
s. You can get your results asynchronously with ObjReturned obj = hashtable.get(key).get()
, which will wait if the FutureTask
in question is not done yet.
You probably don't want one single thread to retrieve the results since it might wait on the task that will turn out to finish last. You could have multiple retrieval threads, or you could cycle through the keys when you wait too long for one task (there is a method FutureTask.get(waitTime, timeUnit)
).
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