Kushan
Kushan

Reputation: 10703

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);

Upvotes: 5

Views: 2805

Answers (2)

Tudor
Tudor

Reputation: 62469

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

Upvotes: 2

Bozho
Bozho

Reputation: 597422

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.

Upvotes: 3

Related Questions