问题
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:
- Use a Hashtable. This isn't generally recommended. Hashtable predates the Java Collections Framework from Java 1.2 but it's
put()
andget()
methods aresynchronized
; - Wrap your
Map
in Collections.synchronizedMap() (which is a better version of (1)); - Use a ConcurrentHashMap; or
- 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