Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (4k points)

I have a Map which is to be modified by several threads concurrently.

There seem to be three different synchronized Map implementations in the Java API:

  • Hashtable

  • Collections.synchronizedMap(Map)

  • ConcurrentHashMap

From what I understand, Hashtable is an old implementation (extending the obsolete Dictionary class), which has been adapted later to fit the Map interface. While it is synchronized, it seems to have serious scalability issues and is discouraged for new projects.

But what about the other two? What are the differences between Maps returned by Collections.synchronizedMap(Map) and ConcurrentHashMaps? Which one fits which situation?

1 Answer

0 votes
by (46k points)

ConcurrentHashMap is designed for concurrency and improves performance while Collections.synchronizedMap(map) which is non-synchronized by sort can be synchronized by applying a wrapper using Collections.synchronizedMap(map). The most typical difference between ConcurrentHashMap and synchronized map in Java is that ConcurrentHashMap doesn't support null keys or null values while synchronized HashMap supports one null key.

For your requirements, use ConcurrentHashMap. It identifies concurrent modification of the Map from various threads without the need to block them. Collections.synchronizedMap(map) produces a blocking Map that will degrade performance, albeit assure consistency (if used properly).

Use the second option if you need to assure data flexibility, and each thread requires to have an up-to-date view of the map. Use the first if performance is critical, and every thread only inserts data to the map, which shows happening less frequently.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
asked Jun 20, 2019 in Java by Ritik (3.5k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...