views:

108

answers:

3

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

+5  A: 

Check if ConcurrentHashMap fits your case.

Bozho
I think it fits, I just thought that probably this is to much for me, like if for my scenario could be something that works faster
Omu
ConcurrentHashMap is definitely the fastest solution for multithreaded scenarios.
Michael Borgwardt
+10  A: 

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).
cletus
+1 for some options that didn't occur to me. Consider making it clearer which is the preferred way?
abyx
You should read http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html to see how bad it can really get ;)
krosenvold
+4  A: 

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.

Michael Borgwardt