Sobes.tech
Junior — Middle

What is the difference between a standard hash table and a thread-safe implementation like ConcurrentHashMap?

sobes.tech AI

Answer from AI

A standard hash table in Java is the HashMap class, which is not thread-safe. Concurrent access from multiple threads without external synchronization can lead to data integrity issues.

ConcurrentHashMap is a thread-safe implementation of a hash table, optimized for use in a multithreaded environment. Main differences include:

  • Locks: ConcurrentHashMap uses segmented locking or other mechanisms (in newer Java versions — CAS and internal structures), allowing multiple threads to read and write simultaneously without locking the entire table.
  • Performance: Thanks to partial locking and non-blocking operations, ConcurrentHashMap provides high performance in a multithreaded environment.
  • Iterators: Iterators of ConcurrentHashMap are weakly consistent, they do not throw ConcurrentModificationException and reflect the state of the map at or after the creation of the iterator.

Example of using ConcurrentHashMap:

import java.util.concurrent.ConcurrentHashMap;

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key1", 1);
map.put("key2", 2);

// Safe for multithreaded access
int value = map.get("key1");