What is the main advantage of using Hashtable
comparing with HashMap
. Because, Hashtable
main advantage is synchronization.
Now map can also synchronized using synchronizedMap()
.
Map m = Collections.synchronizedMap(hashMap);
Hashtable
existed before the collections framework, so it is retained mainly for backward compatibility. Use ConcurrentHashMap
instead.
Note that there is a slight semantic difference - Hashtable
does not allow nulls, while HashMap
allows null values and a null key.
HashTable
has been deprecated a long time ago. The main difference is that HashTable
is synchronized internally, while HashMap
is not. This is however seen as a disadvantage, because using the HashTable
on a single thread incurs the penalty of locking and unlocking when it is not needed.
Also, another point that renders HashTable
's synchronization not so useful is the fact that executing two thread-safe operations in a sequence does not guarantee atomicity of the entire sequence, think for example to:
if(key does not exist)
add key
while both testing existence and adding are thread-safe, the above construct is not, because another thread might interrupt it in the middle. Therefore, external synchronization is needed anyway.
As such, I see no reason to use HashTable
at all these days...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With