Is it Possible to create a Queue for HashMap set?

Right now I am trying to create a producer/consumer thread, the producer thread goes through all possible combinations of letters and creates their respective MD5 hashes. Then each combination and its hash is put into the HashMap<String,String>. Now in my consumer thread I want to be able to use the Queue<> collection on the hashmap so my consumer thread may call poll() etc thus removing values atc like a Queue but still giving me the capability of seeing both the combination and its hash when calling poll() How would I go about doing this? I have the HashMap but dont know how to ‘make’ or cast it as a Queue. Thanks.

Answer

You should not use a HashMap without handling the thread-safety of your code. Else, you may end with a Live-lock.

To be able to iterate your Map with the order in which keys were inserted, you can use a LinkedHashMap.

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

The producer would push entries like this (nothing special):

m.put(key, object)

The consumer would poll entries like this:

while (someCondition) {
    Map.Entry nextEntry = null;

    // This block is equivalent to polling
    {
         synchronized(s) {
             Iterator i = s.iterator(); // Must be in the synchronized block
             if (i.hasNext()) {
                 nextEntry  = i.next();
                 i.remove();
             }
         }
    }

    if (nextEntry != null) {
         // Process the entry
         ...
    } else {
         // Sleep for some time
         ...
    }
    // process
}

Leave a Reply

Your email address will not be published. Required fields are marked *