Multiple threads repeating on the same map

I recently wrote a parallel Java program and came across the following dilemma: suppose you have a global data structure that is part of a regular, unsynchronized, non-competitive library such as HashMap. Is it possible to allow multiple threads to iterate through the collection (just reading, without any changes), possibly at different periods with rotation, that is, thread1 can be halfway through iteration when thread2 gets its iterator on one map?

+8
java multithreading
source share
4 answers

Everything is good. The ability to do this is the reason for creating such an interface as an iterator. Each thread iterating through the collection has its own instance of the iterator, which retains its state (for example, where you are currently in the process of repeating).

This allows multiple threads to iterate over the same collection at the same time.

+12
source share

This should be good if there are no writers.

This problem is similar to blocking readers-writers , where several readers are allowed to read data, but not at the time when the writer has a “lock” for him. There is no problem with concurrency for brevity reading at the same time. [data race can only happen when you have at least one record].

+7
source share

Problems arise only with the simultaneous modification of the data structure.

For example, if one thread iterates over the contents of the Map, and another thread removes items from this collection, you will run into serious problems.

If you need some threads to safely modify this collection, Java provides mechanisms for this, namely ConcurrentHashMap.

ConcurrentHashMap in Java?

There is also a Hashtable that has the same interface as the HashMap, but is synchronized, although it is not currently recommended (deprecated), because its performance suffers when the number of elements becomes larger (compared to ConcurrentHashMap, which does not need to lock the entire collection )

If you have a collection that is not synchronized, and you need to have multiple threads that read and write on top of it, you can use Collections.synchronizedMap (Map) to get a synchronized version.

+4
source share

The above answers are definitely good advice. In general, when writing Java with parallel threads, if you do not change the data structure, you do not need to worry about multiple threads viewing this structure at the same time.

If you have a similar problem in the future, except that the global data structure can be changed at the same time, I would suggest writing a Java class that all threads use to access and restructure. This class could implement its own concurrency methodology using either synchronized methods or locks. The Java tutorial has a very good explanation of Java concurrency mechanisms. I personally did this, and it's pretty straight forward.

+2
source share

All Articles