0

I have query about usage of Collections.synchronizedMap(Map m) over Hashtable. We know that both will return a container where all methods are synchronized, so I don't see performance gain in any case.

Then why we have utility method(Collections.synchronizedMap) when Hashtable suffice the requirement.

Clarification with code will be helpful.

Shashi Shankar
  • 859
  • 2
  • 8
  • 25
  • 1
    Not all maps are synchronized, nor do you always want them to be. – William Price Dec 21 '14 at 08:57
  • Comment on the vote to close this question: I think it is a fairly good question. Answers to this question can bring a lot of insight on where to use different type of collections and raise the issues around Collections.synchronized vs java.util.concurrent. I think this question deserve to stay. – Guillaume Dec 21 '14 at 10:11
  • possible duplicate of [What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?](http://stackoverflow.com/questions/510632/whats-the-difference-between-concurrenthashmap-and-collections-synchronizedmap) – Joe Dec 21 '14 at 10:25

2 Answers2

4

Hashtable and Collections.synchronized() exist mainly for historical reasons. Since Java 5, the new java.util.concurrent package should be used in most cases where you need multiple threads accessing the same collection.

Collections.synchronized() is still useful when you receive a Collection (eg. from third party code) which is not thread safe and you want to share it between multiple threads, without creating a new, thread safe / concurrent collection.

Note that in most cases, you should use java.util.concurrent instead. Synchronized collections will protect their internal state by synchronizing all access to the collection, but that is inefficient in term of performance and does not address the larger problem of the coherence of your data. For example, ConcurrentHashMap provides a putIfAbsent() method that will ensure the atomicity of that operation.

Guillaume
  • 18,494
  • 8
  • 53
  • 74
2

There are more implementations of Map than just HashMap, and you might want to synchronize access to any of them.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152