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.
pcalcao
source share