Santosh
Santosh

Reputation: 17923

Specific usage of Hashtable over ConcurrentHashMap

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 ?

Upvotes: 3

Views: 715

Answers (3)

John Vint
John Vint

Reputation: 40256

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.

Upvotes: 3

Marko Topolnik
Marko Topolnik

Reputation: 200206

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.

Upvotes: 4

yegor256
yegor256

Reputation: 105133

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)?

Upvotes: 1

Related Questions