Monday, 22 February 2016

Difference between HashMap and ConcurrentHashMap in Java

ConcurrentHashMap was added in Java 5 as an alternative for HashTable to improve the performance of the (key, value) pair kind of data structure while still keeping it thread safe. On the other hand HashMap which is not synchronized provides better performance but it is not thread safe.

In this post we'll see the differences between the ConcurrentHashMap and HashMap which is also a good Java interview question.

Difference between ConcurrentHashMap and HashMap

  1. First and foremost difference is of course thread safety. ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment whereas HashMap is not thread safe.
  2. Second difference is about how these data structures synchronize. HashMap can be synchronized using the Collections.synchronizedMap() method but that synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time.

    In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.

    By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. That means theoretically any given time 16 threads can access ConcurrentHashMap if they all are going to separate buckets.

  3. In ConcurrentHashMap performance is further improved by providing read access concurrently without any blocking. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
  4. HashMap allows one null as key but ConcurrentHashMap doesn't allow null as key.

  5. Performace wise HashMap is better as there is no synchronization.

    In case HashMap has to be used in a multi-threaded environment and there is a need to use Collections.SynchronizedMap() method then ConcurrentHashMap() is a better choice as ConcurrentHashMap still gives a chance to more than one thread to access map thus improving performance.

  6. Iterator provided by ConcurrentHashMap is fail-safe which means it will not throw ConcurrentModificationException if the underlying structure is changed during iteration.

    Iterator provided by HashMap is fail-fast as it throws a ConcurrentModificationException if the underlying collection is structurally modified at any time after the iterator is created.

That's all for this topic Difference between HashMap and ConcurrentHashMap in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. ConcurrentHashMap in Java
  2. CopyOnWriteArrayList in Java
  3. How HashMap internally works in Java
  4. Semaphore in Java concurrency
  5. ReentrantLock in Java concurrency
  6. Java Concurrency interview questions

You may also like -

No comments:

Post a Comment