Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a HashMap with a getAndWait() method exist? E.g. a BlockingConcurrentHashMap implementation?

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.

like image 239
David Parks Avatar asked Jun 17 '11 16:06

David Parks


People also ask

What is the implementation of the HashMap?

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.

Which of the following are not being implemented by HashMap class?

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.

Which two methods you need to implement to use an object in HashMap?

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java.

Does HashMap implements cloneable?

HashMap extends an abstract class AbstractMap and implements Cloneable and Serializable interfaces.


1 Answers

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 FutureTasks. 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)).

like image 167
toto2 Avatar answered Sep 28 '22 05:09

toto2