← Databricks Interview Insights
I started with the obvious stuff, HashMap isn't thread-safe because concurrent rehashing can corrupt the internal structure, and in older JDKs you could get threads stuck in infinite loops reading a circular linked list.
Start by explaining why a plain HashMap fails under concurrency, then compare coarse-grained synchronization approaches, and finally dive into ConcurrentHashMap's internal design. Emphasize trade-offs and how the design achieves high concurrency.
Pro tip: Mention that ConcurrentHashMap uses lock striping and CAS operations to minimize contention, and that its iterators are weakly consistent, which avoids ConcurrentModificationException. This shows deep understanding beyond textbook knowledge.
Explain that HashMap is not thread-safe: concurrent writes can cause data corruption, infinite loops (pre-Java 8), and lost updates. Also, its fail-fast iterators throw ConcurrentModificationException.
Describe using Collections.synchronizedMap or a single lock around the entire map. This ensures thread safety but serializes all operations, severely limiting concurrency.
Explain that ConcurrentHashMap is designed for high concurrency with thread safety, allowing multiple readers and a configurable number of writers to proceed concurrently.
Describe lock striping (segments in Java 7, bins in Java 8+), use of CAS for lock-free reads and some writes, and synchronization on individual bins for writes. Mention that reads are typically lock-free and writes lock only the affected bin.
Highlight that ConcurrentHashMap offers better scalability than synchronized maps, but has overhead for certain operations (e.g., size() is not constant-time). Mention weakly consistent iterators and when to choose it.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.