Search code examples
javamultithreadingjava-8hashmaphashtable

Java 8 HashTable vs HashMap Collision Handling


I want some clarification about the differences between hashtable and hashmap in Java 8.

HashTable to my knowledge functions similarly to a HashMap but is threadsafe, and doesn't allow null keys or values. I am aware that Java 8 updates the HashMap class so that when there's a collision, rather than create a linked list of items with the same hash code in the bucket, it creates a tree.

Is this also the case with hashtable? And is the tree the default storage method even before a collision? (As in, when the first item to fit into a bucket is placed there, it's just a tree root with no branches.)

Also, how does java ensure that a hashtable is threadsafe? Does it create a que when two threads try to concurrently access a piece of data?


Solution

  • This answer is going to be very specific to the current implementation found in the JDK so keep that in mind.

    1. I am aware that Java 8 updates the HashMap class so that when there's a collision, rather than create a linked list of items with the same hash code in the bucket, it creates a tree.

      Is this also the case with hashtable?

    No. The Hashtable is only ever going to be a table of linked lists. Java devs didn't update the Hashtable for this use case. This should also make it more clear that you probably shouldn't be using Hashtable anyway.

    1. And is the tree the default storage method even before a collision?

    Again this is in Java 8, as of today, but, no it's not the default behavior. Once the bucket entry hits 8 linked elements the HashMap turns that linked list into a binary tree.

    1. Also, how does java ensure that a hashtable is threadsafe? Does it create a que when two threads try to concurrently access a piece of data?

    By making every method synchronized, meaning, each thread will queue up on the method while another thread is currently accessing any method of the Hashtable. This causes quite a few issues if you want to do things like atomic puts, or atomic computes.

    If you wanted a thread safe map HashMap, always use ConcurrentHashMap, never Hashtable.