Interview Lesson: JVM Memory, equals/hashCode and HashMap Internals
The three topics interviewers use most to test Java depth — where things live in memory, the equals/hashCode contract, and how HashMap really works.
What you’ll learn
- Heap, stack, Metaspace and the string pool
- Diagnosing OutOfMemoryError and StackOverflowError
- The equals/hashCode contract and the mutable-key bug
- HashMap put, resize and treeification (Java 8+)
- HashMap vs ConcurrentHashMap vs synchronizedMap
Part of the interview roadmap
This is Lesson 1 of the Java Spring Boot Interview Roadmap (5 YOE). It covers topics 1, 3, 4 and 5 — must-know, medium to hard.
Part A: JVM memory
The heap holds all objects and is shared by all threads. In generational collectors it is split into a young generation (Eden plus two survivor spaces) and an old generation. New objects go to Eden; survivors of minor collections move between the survivor spaces and are promoted to the old generation after reaching a tenuring threshold.
Each thread has its own stack of frames, holding local primitives and references to heap objects.
Class metadata lives in Metaspace, which is native memory (since Java 8, replacing PermGen). The string pool lives in the heap (since Java 7). Since Java 9, G1 is the default garbage collector.
Common wrong answer
"Objects are on the heap, primitives are on the stack." A primitive field inside an object lives on the heap with that object; only local primitives live in the stack frame.
Reading memory errors
| Error | Cause | First diagnostic step |
|---|---|---|
OutOfMemoryError: Java heap space | Live objects exceed the heap: a leak or an undersized heap | Take a heap dump (jcmd <pid> GC.heap_dump) and analyse the dominator tree |
OutOfMemoryError: Metaspace | Class-loader leak or runaway dynamic class generation | Check class-count growth and redeploy patterns |
StackOverflowError | Unbounded recursion or very deep call chains | Read the repeating frames in the stack trace |
Part B: equals and hashCode
The contract:
- Equal objects must return equal hash codes.
hashCodemust be stable while the object is in a hash-based collection.equalsmust be reflexive, symmetric, transitive, consistent, and returnfalsefornull.- Unequal objects may share hash codes (collisions), but good distribution keeps lookups fast.
The mutable-key bug
import java.util.*;
public class MutableKeyDemo {
static class Key {
String id;
Key(String id) { this.id = id; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Key k)) return false; // Java 16+ pattern matching
return Objects.equals(id, k.id);
}
@Override public int hashCode() { return Objects.hash(id); }
}
public static void main(String[] args) {
Map<Key, String> map = new HashMap<>();
Key k = new Key("A1");
map.put(k, "order-1");
k.id = "A2"; // mutates the hash input
System.out.println(map.get(k)); // null: looked up in the wrong bucket
System.out.println(map.get(new Key("A1"))); // null: right bucket, but equals is now false
System.out.println(map.size()); // 1: the entry is effectively lost
}
}Fix: make key fields final, or use an immutable record — records generate consistent equals and hashCode from their components.
Tip
If equals uses getClass() rather than instanceof, subclass equality changes. In an interview, state which one you chose and why.
Part C: HashMap internals (Java 8+)
- Storage: an array of buckets, default capacity 16, load factor 0.75. The index is
(n - 1) & hash, where the hash is spread ash ^ (h >>> 16)so high bits influence the index. Capacity is always a power of two, which makes the index calculation a cheap bit mask. - Put: compute the bucket and insert if it's empty; otherwise compare hash, then
equals, along the chain, and append at the tail if not found. - Resize: when size exceeds capacity × load factor (12 for the default), the table doubles and entries are redistributed. Each entry stays at its old index or moves by exactly the old capacity.
- Treeification: a bin converts to a red-black tree when it reaches 8 entries and the table capacity is at least 64 (below 64 the table resizes instead). It converts back when it shrinks to 6 or fewer. Worst-case lookup goes from O(n) to O(log n); tree ordering uses
Comparablewhen keys implement it. - Not thread-safe: concurrent puts can lose updates. In Java 7, a concurrent resize could produce an infinite loop in a bucket chain; Java 8's tail insertion fixed that case, but it does not make the map safe.
- ConcurrentHashMap (Java 8+): CAS for empty bins,
synchronizedon the first node of a non-empty bin, no segment locks. Null keys and values are not allowed, andsize()is approximate under concurrent updates.
HashMap | ConcurrentHashMap | Collections.synchronizedMap | |
|---|---|---|---|
| Thread safety | Not thread-safe | Thread-safe, fine-grained locking, scalable reads | Thread-safe, one lock for the whole map |
| Nulls | One null key, null values allowed | No nulls | Depends on the wrapped map |
| Iterators | Fail-fast | Weakly consistent | Must lock manually while iterating |
Interview questions
Q1. Why must you override hashCode when you override equals? (Easy)+
Hash-based collections find the bucket via hashCode before calling equals. If equal objects return different hash codes they land in different buckets, so lookups fail.
Likely follow-up: what happens if hashCode returns a constant? (Everything collides into one bucket — correct, but lookups degrade to O(n), or O(log n) once treeified.)
Common mistake: saying "it improves performance" only. It's about correctness.
Q2. What happens if you mutate a key after inserting it? (Medium)+
The stored hash no longer matches the key's current hash, so the entry becomes unreachable by normal lookups and leaks memory.
Likely follow-up: how do you design a safe key? (Immutable fields, or a record.)
Common mistake: claiming HashMap re-hashes automatically.
Q3. Explain HashMap put, step by step. (Medium)+
Spread the hash, compute the index, handle an empty bin, compare hash and equals along the chain or tree, insert, then resize if size exceeds the threshold.
Likely follow-up: when does a bin become a tree?
Common mistake: forgetting the "table capacity at least 64" condition.
Q4. Why is the capacity a power of two? (Medium)+
index = (n - 1) & hash replaces modulo with a bit mask, and on resize every entry ends up in one of exactly two positions.
Likely follow-up: what happens if you pass a capacity of 20? (It's rounded up to the next power of two, 32.)
Common mistake: saying it reduces collisions by itself.
Q5. Is String immutable, and why does it matter? (Easy)+
Yes. Immutability enables safe hash caching, thread safety, string-pool sharing, safe use as a map key, and safety for security-sensitive parameters.
Likely follow-up: does intern() always help?
Common mistake: saying "strings are stored on the stack".
Q6. HashMap vs ConcurrentHashMap vs synchronizedMap? (Medium)+
See the table above; choose ConcurrentHashMap for concurrent access with high read volume.
Likely follow-up: is a compound check-then-put safe in ConcurrentHashMap? (No — use putIfAbsent or compute.)
Common mistake: saying ConcurrentHashMap locks the whole map.
Q7. Scenario: a lookup that worked yesterday returns null after a refactor. What do you check? (Hard)+
Whether the key class changed its equals/hashCode, whether key fields became mutable, whether a different key type is now used, and whether the map is accessed concurrently.
Likely follow-up: how would you write a test to prevent the regression?
Common mistake: assuming the data is missing without checking the key class.
Exercises
⚡ E1 · Immutable value object
Write an immutable Money class (amount, currency) with correct equals, hashCode, toString and defensive copies. Then rewrite it as a record and list the behaviour differences.
⚡ E2 · Reproduce the bug
Reproduce the mutable-key bug above, then fix it and add a unit test that fails before the fix.
⚡ E3 · Build a HashMap
Implement a minimal HashMap with chaining: put, get, remove, and resize at load factor 0.75, with tests. Stretch: convert long chains to a balanced structure.
⚡ E4 · Feel the collisions
Create a key class with a constant hashCode, insert 100,000 entries, and time the puts against a proper hashCode. Explain the difference using treeification.
⚡ E5 · Lost updates
Spawn 8 threads doing 100,000 increments each on a HashMap counter and observe the lost updates. Fix it with ConcurrentHashMap.merge, then compare with AtomicLong and a LongAdder variant.
Your turn
Answer questions 2, 3 and 7 out loud in your own words — about two minutes each — without notes. Score yourself from 1 to 10 on correctness, depth, clarity, practical understanding and trade-offs, then record the score in the readiness scorecard. Anything below 6 goes in your mistake log.
Key takeaways
- Only local primitives live on the stack; object fields live on the heap.
- Equal objects must have equal hash codes, and hash inputs must never change while the key is in a map.
- HashMap: capacity is a power of two, resize at 0.75, treeify at 8 entries only when capacity is at least 64.
- Use ConcurrentHashMap (with
merge/compute) for concurrent access.
Finished this lesson?
Mark it complete to move forward on your roadmap.