Thursday 14 August 2014

Java Collections - HashMap vs Hastable vs Collections.synchronizedMap vs ConcurrentHashMap

This is a very famous interview topic for the experienced persons who have "really" worked in java technologies. By this question, interviewer can verify weather you have really worked with collections or not also your knowledge on synchronization problem with Hash Map (Collections).

This article can help you for the following questions.
1.) How HashMap works in java.
2.) Have you work with collection classes(HashMap) in the multi threaded environment?
     What are the problems you faced in HashMap? What is ConcurrentModificationException?
     What is fail-fast and fail-safe iterator?
     Why do we need Hashtable or Collections.synchronizedMap Or ConcurrentHashMap?
3.) Similarity/difference between Hashtable and Collections.synchronizedMap.
     If functionality of both (Hashtable and Collections.synchronizedMap) is same then why do we need both?
4.) Similarity/difference between ConcurrentHashMap and Hashtable.
     Similarity/difference between ConcurrentHashMap and Collections.synchronizedMap.
5.) When one can use Hashtable, Collections.synchronizedMap and ConcurrentHashMap.



HashMap
Hashtable
Collections.synchronizedMap
ConcurrentHashMap
Legacy class
-
Yes
-
Java 1.5 and above
Allow
null key/ value
One null key and many null values are allowed.
Not allowed

Allowed
Not allowed
(Neither key nor value)
Thread Safe
No
Yes
Yes
Yes
Lock the entire map?

Yes
Yes
No
(Locks some portion(segment) of the map)
Speed

Slow
(Compare to Concurrent HashMap)
Slow
(Compare to Concurrent HashMap)
Fast
(Compare to Hashtable and Collections.synchronizedMap)
Performance

Low
(Compare to Concurrent HashMap)
Low
(Compare to Concurrent HashMap)
High
(Compare to Hashtable and Collections.synchronizedMap)
Multiple threads can access?
(Is synchronized?)

Yes
Yes
Yes
Multiple threads can access (read) without blocking other thread?

No
(At a time, only one thread can read)
No
(At a time, only one thread can read)

Yes
(At a time, more than one thread can read)
Multiple threads can access (write) without blocking other thread?

No
No
May be
(If writers(threads) write on different segments than only)





Scalable

Less scalable then Concurrent HashMap
Less scalable then Concurrent HashMap
More scalable then Hashtable and Collections.synchronizedMap





No comments:

Post a Comment