java: adding values to a map by multiple threads (is it possible ?)

丶灬走出姿态 提交于 2019-12-13 02:15:11

问题


is it thread safe to add elements to a Map by multiple threads at the same time ?
Like if 10 threads add an element to a Map at exactly the same time, is the Map going to have 10 elements or 1 ?

UPDATE: I don't need to iterate through this map, all I need is to add, remove and get elements by key


回答1:


Check if ConcurrentHashMap fits your case.




回答2:


There are several ways to handle this:

  1. Use a Hashtable. This isn't generally recommended. Hashtable predates the Java Collections Framework from Java 1.2 but it's put() and get() methods are synchronized;
  2. Wrap your Map in Collections.synchronizedMap() (which is a better version of (1));
  3. Use a ConcurrentHashMap; or
  4. Implement your own synchronization scheme (not recommended).



回答3:


Your question makes no sense because Map is an interface type, and thread safety is an implementation property.

That being said, the most commonly used Map implementations, specifically HashMap are not thread safe. Adding elements from different threads can leave the map in an inconsistent state where e.g. elements that have been inserted cannot be retrieved though size() shows that they're present.

You can use Collections.synchronizedMap() to create a synchronized wrapper, or use the old Hashtable class (not recommended) which is also synchronized. But note that these are still only threadsafe for single operations - sequences of operations that depend on each other, like iteration through the map, still need additional manual synchronization.

ConcurrentHashMap is a very interesting implementation that allows certain kinds of multithreaded access without using sychronization, resulting in very good performance when there are lots of threads accessing it in parallel. But it's not applicable for all use cases.



来源:https://stackoverflow.com/questions/1838261/java-adding-values-to-a-map-by-multiple-threads-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!