简体   繁体   中英

Enforce element from a map used by a thread should not be used by another thread until first thread completes execution

I have a Map say

HashMap<String, String> init = new Hashmap<String, String>

and map has 3 elements. [("one","alpha"),("two","beta"),("three","theta")]

Now I have to run five threads in parallel, using any of pair from above map such that only free pair should be used by new thread.

I mean, no two threads running in parallel should have same pair of values. Need to enforce whatever thread is running, the pair of values used by that thread should not be used by another thread at same time

Map has pool of values and any pair free in it should be assigned to thread

I think a better solution is to replace the Map with a BlockingQueue and use a custom type to represent the pairs / tuples.

  • You instantiate the queue with a concurrent queue type and populate it with all of the pairs / tuples.
  • Each thread takes a pair from the front of the queue, blocking if none is available.
  • When the thread is finished, it adds the pair to the back of the queue.

The synchronization happens with the Queue::take operation.

This design ensures that no pair is used by two threads at the same time.

You could just removed every element from the Map, when a Thread is choosing to use it. Therefore you would need to use a Hashtable instead of a Hashmap, so that there will be no problem when multiple threads are modifing it at the same time. (Hash Table is synchronized, HashMap not).

Map<String, String> init = new Hashtable<String, String>()

PS: always use the according interfaces for variable definitions, so that you can swap out the specific class when needed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM