HardConcept

What is the difference between HashMap, Hashtable and ConcurrentHashMap in Java?

Technology:
Java
Experience:
Mid-level,
Senior

Quick answer

HashMap is not thread-safe, Hashtable is thread-safe by locking the whole map on every method, and ConcurrentHashMap is thread-safe with much finer-grained locking and lock-free reads, so it scales far better.

Detailed explanation

Using a plain HashMap from several threads can lose updates or, in older versions, even loop forever during a resize. Hashtable and Collections.synchronizedMap() fix this by synchronising every operation on a single lock, so threads queue up behind each other.

ConcurrentHashMap locks only the bucket being modified (using CAS and synchronized on the bucket head since Java 8) and allows reads without locking, so many threads can work in parallel. It does not allow null keys or values. Its compound atomic methods such as computeIfAbsent, merge and putIfAbsent should be used instead of a separate get followed by put, which is a race condition.

Example

java
ConcurrentHashMap<String, Integer> hits = new ConcurrentHashMap<>();
hits.merge("home", 1, Integer::sum);   // atomic increment

// racy even on a ConcurrentHashMap:
// if (!map.containsKey(k)) map.put(k, v);
  • JavaMedium

    What is the difference between ArrayList and LinkedList in Java?

    ArrayList is backed by a resizable array with O(1) index access and O(n) insertion in the middle, while LinkedList is a doubly linked list with O(n) index access and O(1) insertion once you hold the node; in practice ArrayList is faster for most workloads.

    Junior 路 Mid-level 路 Data Structures
  • JavaMedium

    How does HashMap work internally in Java?

    A HashMap stores entries in an array of buckets; it computes the key's hash code to choose a bucket, resolves collisions with a linked list that becomes a red-black tree when a bucket grows large, and resizes when the load factor of 0.75 is exceeded.

    Mid-level 路 Senior 路 Data Structures
  • JavaMedium

    What is the difference between an abstract class and an interface in Java?

    An abstract class can have instance fields, constructors and a mix of implemented and abstract methods but supports only single inheritance, while an interface defines a contract that a class can implement multiple times and, since Java 8, can include default methods.

    Junior 路 Mid-level 路 Object-Oriented Programming
  • JavaMedium

    What is the difference between checked and unchecked exceptions in Java?

    Checked exceptions (subclasses of Exception other than RuntimeException) must be caught or declared with throws, while unchecked exceptions (RuntimeException and Error) do not have to be handled and usually signal programming bugs.

    Junior 路 Mid-level 路 Programming Fundamentals