Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of HashTable

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);
like image 727
Kushan Avatar asked Jan 16 '12 08:01

Kushan


2 Answers

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.

like image 155
Bozho Avatar answered Nov 13 '22 08:11

Bozho


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...

like image 45
Tudor Avatar answered Nov 13 '22 08:11

Tudor