In this blog post, I am noting down the key differences between Hashtable, HashMap and ConcurrentHashMap.
References: Java Docs
HashTable
|
HashMap
|
ConcurrentHashMap
|
|
1
|
It is a legacy class which as a part of Java 2 was retrofitted
to implement Map interface, making it a member of java Collections framework.
|
It is a member of Java collections framework since Java 2.
|
It is a member of java collections framework since Java 5
|
2
|
Belongs to java.util package
|
Belongs to java.util package
|
Belongs to java.util.concurrent package
|
3
|
This class extends Dictionary class, which extends Object.
|
This class extends AbstractMap, which extends Object.
|
This class extends AbstractMap, which extends Object.
|
4
|
Implemented interfaces: Serializable, Cloneable, Map
|
Implemented interfaces: Serializable, Cloneable, Map
|
Implemented interfaces: Serializable, ConcurrentMap, Map
|
5
|
Does not permit null key or value.
|
Permits null values and null key.
|
Does not permit null key of value.
|
6
|
Synchronized = threadsafe
|
Unsynchronized = not thread safe. External synchronization
needed if multiple threads access a HashMap concurrently. Can be synchronized
by Map m = Collections.synchronizedMap( new HashMap(…));
|
Synchronized = threadsafe. Provides better scalability
than hashtable. Does not lock entire
table.
|
7
|
Elements can be iterated using enumeration as well as
Iterator.
|
Can be iterated only with Iterator.
|
Can be iterated only with Iterator
|
8
|
Slow compared to HashMap if used for single threaded
applications.
|
Fast performance compared to Hashtable for single threaded
applications.
|
|
9
|
HashMap makes no guarantee as to the order in the map. So
in the event you would want predictable iteration order (which is insertion
order by default), you could use one of the subclasses of hashmap called
LinkedHashMap.
|
||
More description to the points
above:
5. Hashtable and
ConcurrentHashMap do not allow nulls whereas HashMap does allow null keys and
values. The main reason that nulls
aren’t allowed in CocurrentMaps is if map.get(key) returns null, you cant
detect whether the key explicitly maps to null vs the key isn’t mapped at all.
In a non-concurrent map, you can check via map.contains(key), but in a
concurrent one, the map might have changed between calls.
7. Enumeration is not fail-fast whereas Iterator is fail-fast;
if the map is structurally modified at any time after the iterator is created,
in any way except through the iterator’s own remove method, the iterator will
throw a ConcurrentModificationException. The failing-fast behavior of iterators
is not guaranteed as it is impossible to make hard guarantees in the presence
of unsynchronized concurrent modification. (This is more on difference between
the Enumeration and Iterator)
References: Java Docs
No comments:
Post a Comment