3

ConcurrentHashMap was introduced in 1.5 as a part java java.util.concurrent package. Before that the only way to have a threadsafe map was to use HashTable or Collections.synchronizedMap(Map).

For all the practical purpose (multithread environment),ConcurrentHashMap is sufficient to address the needs except one case wherein a thread needs a uniform view of the map.

My question is, apart from having a Uniform View of the map, are there any other scenarios wherein ConcurrentHashMap is not an option ?

Santosh
  • 17,667
  • 4
  • 54
  • 79
  • You might find some cases where one or the other is less performant than you require. Perhaps when heavily loaded. You would need to measure these things though. – BillRobertson42 Aug 17 '12 at 14:34
  • What is "uniform view"? Could you please explain... – yegor256 Aug 17 '12 at 14:41
  • 1
    @yegor256, a uniform view is a view of the entries of the map which is not changing when the thread is access this particular map. – Santosh Aug 17 '12 at 14:56

3 Answers3

4

The usage of Hashtable has been discouraged since Java 1.2 and the utility of synchronizedMap is quite limited and almost always ends up being insufficient due to the too-fine granularity of locking. However, when you do have a scenario where individual updates are the grain size you need, ConcurrentHashMap is a no-brainer better choice over synchronizedMap. It has better concurrency, thread-safe iterators (no, synchronizedMap doesn't have those—this is due to its design as a wrapper around a non-thread-safe map), better overall performance, and very little extra memory weight to pay for it all.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

This is a stretch but I will give it as a use case.

If you needed a thread-safe Map implementation which you can do some extra compound operation on which isn't available via ConcurrentMap. Let's say you want to ensure two other objects don't exist before adding a third.

Hashtable t = new Hashtable();

synchronized(t){
   if(!t.contains(object1) && !t.contains(object2)){
      t.put(object3,object3);
   }
}

Again this is a stretch, but you would not be able to achieve this with a CHM while ensuring atomicity and thread-safety. Because all operations of a Hashtable and its synchronizedMap counter part synchronize on the instance of the Map this ensures thread-safety.

At the end of the day I would seldom, if ever, use a synchronizedMap/Hashtable and I suggest you should do the same.

John Vint
  • 39,695
  • 7
  • 78
  • 108
1

As far as I understand, ConcurrentMap is a replacement of HashTable and Collections.synchronizedMap() for thread-safe purposes. A usage of that all classes is discouraged. Thus, the answer to your question is "no, there are no other scenarios".

See also: What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

Community
  • 1
  • 1
yegor256
  • 102,010
  • 123
  • 446
  • 597