Skip to content
Visual explainer 6h to learn 5 steps

Java & Spring Boot interview questions

Explain collections internals, concurrency, JVM and Spring internals.

By Invicly Tech, , in Interview Preparation. About 13 minutes to read.

Topic 22 of 27

In short

Java interviews probe internals: how HashMap works, equals and hashCode, thread safety, JVM memory and how Spring builds beans and proxies. Explain the why, not just the API.

Explained simply

Java interviews rarely ask you to recite an API. They ask why it works the way it does. Why does HashMap need hashCode? Why is String immutable? Why does @Transactional sometimes do nothing? If you can explain the mechanism, you can answer the follow-up questions too.

Most questions come from five areas: collections (HashMap, ConcurrentHashMap), object rules (equals, hashCode, immutability), threads (locks, volatile, executors), the JVM (memory areas and garbage collection) and Spring (beans, dependency injection, proxies, transactions).

A good answer has three parts: what it does, how it works inside, and when it goes wrong. For example: HashMap stores entries in buckets, picks the bucket from the hash code, and becomes slow if many keys share a bucket. That last part is what shows real experience.

Practise saying answers out loud in about one minute each, then be ready to go one level deeper. Short code snippets on a whiteboard, like a correct equals method or a thread-safe counter, make your answer concrete.

Press Play on a diagram to walk through it one step at a time.

FlowHashMap.put internals
  1. 1
    Compute hashCode()

    High bits mixed in to spread values

  2. 2
    Find bucket

    index = hash & (capacity - 1)

  3. 3
    Empty bucket?

    Store a new node directly

  4. 4
    Else compare keys

    equals() match replaces value, else append

  5. 5
    Treeify long buckets

    8+ nodes become a red-black tree

  6. 6
    Resize past 0.75

    Double capacity and redistribute entries

CompareThread-safe map options
HashMap
  • Not thread-safe
  • Allows one null key
  • Fastest single-threaded
Collections.synchronizedMap
  • One lock for all operations
  • Simple but contended
  • Iterate inside synchronized block
ConcurrentHashMap
  • Fine-grained locking and CAS
  • No null keys or values
  • Atomic compute and merge
SequenceWhy self-invocation skips @Transactional
Controller
Proxy
OrderService
  1. 1placeOrder()
    Controller to Proxy: placeOrder()
  2. 2Begin transaction
    Proxy to Proxy: Begin transaction
  3. 3placeOrder() on real bean
    Proxy to OrderService: placeOrder() on real bean
  4. 4this.audit(): no proxy, no new tx
    OrderService to OrderService: this.audit(): no proxy, no new tx
  5. 5Return normally
    OrderService to Proxy: Return normally
  6. 6Commit and return
    Proxy to Controller: Commit and return

In depth

HashMap deeper: capacity, resize and tree bins

A HashMap starts with 16 buckets and a load factor of 0.75, so it resizes when it holds more than 12 entries. Capacity is always a power of two, which lets it find the bucket with hash & (n - 1) instead of a slow modulo. Before that, it mixes the high bits of hashCode into the low bits, so keys that differ only in high bits still spread out.

On resize, the table doubles and each entry either stays at index i or moves to i + oldCapacity, depending on one bit. If one bucket grows to 8 entries and the table has at least 64 buckets, that bucket becomes a red-black tree, so worst-case lookups are O(log n) instead of O(n). If the table is smaller, it resizes instead. Trees turn back into lists when they shrink to 6.

HashMap allows one null key (stored in bucket 0) and is not thread-safe. Its iterators are fail-fast: changing the map while iterating throws ConcurrentModificationException.

  • Pre-size with new HashMap<>(expected * 4 / 3 + 1) to avoid resizes
  • Treeify needs 8 nodes in a bucket and capacity 64 or more
  • Mutable keys break lookups if their hashCode changes after insertion

How ConcurrentHashMap stays fast and safe

In Java 7 ConcurrentHashMap used segments, each with its own lock. Since Java 8 it locks per bucket instead. Reads never lock: the table and node values are read with volatile semantics, so a get sees the latest completed write. To insert into an empty bucket, it uses a CAS (compare-and-swap) instruction with no lock at all. To change a non-empty bucket, it synchronises on that bucket's first node only, so threads writing to different buckets never wait for each other.

Resizing is shared: threads that touch the map during a resize help move buckets. size() is computed from a set of counter cells, like LongAdder, so it is an estimate during heavy writes. Iterators are weakly consistent: they never throw ConcurrentModificationException and may or may not show changes made during iteration.

Use compute, merge and putIfAbsent for atomic read-modify-write. A separate get followed by put is two operations and is not atomic.

FlowConcurrentHashMap.put since Java 8
  1. 1
    Spread the hash

    Same bit mixing as HashMap

  2. 2
    Bucket empty?

    CAS the new node in, no lock

  3. 3
    Resize running?

    Help move buckets, then retry

  4. 4
    Lock first node

    synchronized on that one bucket

  5. 5
    Insert or replace

    Treeify long bins, update counters

Threads: synchronized, locks, volatile and the memory model

The Java Memory Model defines happens-before rules. An unlock happens-before the next lock of the same monitor, and a volatile write happens-before every later read of that field. Without such a rule, one thread may never see another's write, because of CPU caches and compiler reordering.

synchronized gives both mutual exclusion and visibility, and it is reentrant (the same thread can enter again). ReentrantLock adds tryLock with a timeout, interruptible waiting and optional fairness, but you must unlock in a finally block. volatile only gives visibility and ordering: count++ on a volatile field is still a read, an add and a write, so two threads can lose updates. Use AtomicInteger (CAS based) or LongAdder for counters.

For real code, prefer an ExecutorService or virtual threads (final in Java 21) over raw new Thread. Virtual threads are cheap enough for one per request, which suits blocking I/O code.

  • wait and notify must be called while holding the object's monitor
  • Always call wait inside a while loop that re-checks the condition
  • Double-checked locking needs the field to be volatile
  • A static synchronized method locks the Class object, not the instance

JVM memory areas and garbage collection

The heap holds objects and is shared by all threads. Most collectors split it into a young generation (Eden plus two survivor spaces) and an old generation, because most objects die young. A minor GC copies live young objects to a survivor space; objects that survive several cycles are promoted to old. Each thread also has its own stack of frames for local variables; deep recursion gives StackOverflowError. Class metadata lives in Metaspace, in native memory, which replaced PermGen in Java 8.

G1 is the default collector since Java 9. It splits the heap into regions and aims for a pause target (200 ms by default, set with -XX:MaxGCPauseMillis). ZGC targets sub-millisecond pauses on very large heaps, and since JDK 23 runs in generational mode by default. Know -Xms and -Xmx for initial and maximum heap, and the different OutOfMemoryError messages: Java heap space, Metaspace, and unable to create native thread.

LayersWhere JVM memory goes
  1. 1
    Thread stacks

    One per thread, frames and locals

  2. 2
    Young generation

    Eden and two survivor spaces

  3. 3
    Old generation

    Long-lived objects, promoted from young

  4. 4
    Metaspace

    Class metadata, native memory

  5. 5
    Code cache and direct buffers

    JIT-compiled code, NIO buffers

Spring beans, proxies and @Transactional

The Spring container creates beans in steps: instantiate, inject dependencies, run BeanPostProcessors before init, call @PostConstruct, then run BeanPostProcessors after init. That last step is where Spring may replace your bean with a proxy. Beans are singletons by default, one instance per container, so they must not keep per-request state in fields.

A proxy is a wrapper around your bean. Spring uses a JDK dynamic proxy when it proxies through an interface, and a CGLIB subclass otherwise; Spring Boot uses CGLIB by default. When another bean calls a @Transactional method, the call goes through the proxy, which opens a transaction, calls your method, and commits or rolls back.

This explains the classic traps. A call from one method to another in the same class uses this, not the proxy, so the annotation is skipped. Private methods cannot be intercepted. By default, rollback happens only for unchecked exceptions (RuntimeException and Error); add rollbackFor for checked ones. The default propagation is REQUIRED (join or start); REQUIRES_NEW suspends the outer transaction.

  • Constructor injection makes dependencies final and easy to test
  • Fix self-invocation by moving the method to another bean
  • @Transactional(readOnly = true) can enable read optimisations

Learn it in 5 short steps

About 1h 10m each. Track them with a timer in your plan.

  1. 1
    Explain HashMap and ConcurrentHashMap internals~1h 10m
  2. 2
    Review equals, hashCode and immutability~1h 10m
  3. 3
    Answer threading and synchronization questions~1h 10m
  4. 4
    Explain JVM memory and GC~1h 10m
  5. 5
    Explain Spring beans, proxies and @Transactional~1h 10m

Key points

  • Equal objects must have equal hash codes, or hash-based collections lose them.
  • volatile gives visibility, not atomicity; use atomics or locks for compound updates.
  • Spring wraps beans in proxies for @Transactional, so self-calls bypass it.
  • Immutable objects are thread-safe by design: final fields, no setters, defensive copies.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
final class Point {
  private final int x, y;
  Point(int x, int y) { this.x = x; this.y = y; }

  @Override public boolean equals(Object o) {
    return o instanceof Point p && p.x == x && p.y == y;
  }
  @Override public int hashCode() { return Objects.hash(x, y); }
}
// Without hashCode, map.get(new Point(1, 2)) can return null.
// Shortcut: record Point(int x, int y) {} generates both.

A thread-safe hit counter, three ways

The interviewer asks you to count page hits from many threads. Step 1: show the bug, a plain int with count++ loses updates because it is read, add, write. Step 2: fix with synchronized, correct but every thread waits on one lock. Step 3: fix with AtomicInteger, which uses CAS and no lock. Step 4: for very high contention, use LongAdder, which spreads updates across cells and sums them on read. For counts per page, use ConcurrentHashMap.merge, which is atomic per key.

java
class Counter {
  private int plain;                            // broken: lost updates
  private final AtomicInteger atomic = new AtomicInteger();
  private final LongAdder adder = new LongAdder();
  private final ConcurrentHashMap<String, Long> perPage = new ConcurrentHashMap<>();

  void hit(String page) {
    plain++;                                    // not atomic
    atomic.incrementAndGet();                   // CAS loop
    adder.increment();                          // best under heavy contention
    perPage.merge(page, 1L, Long::sum);         // atomic per key
  }
}

Diagnosing an OutOfMemoryError in production

A service dies with java.lang.OutOfMemoryError: Java heap space after running for two days. Step 1: say it is probably a leak, not a too-small heap, because it grows slowly. Step 2: make sure the JVM writes a heap dump on OOM with -XX:+HeapDumpOnOutOfMemoryError. Step 3: open the dump in Eclipse MAT or VisualVM and look at the dominator tree for the biggest retained objects. Step 4: typical culprits are a static map used as a cache with no eviction, listeners never removed, or ThreadLocal values in pooled threads. Step 5: fix with a bounded cache such as Caffeine, and watch heap after GC in your metrics.

bash
java -Xms1g -Xmx1g \
  -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps \
  -Xlog:gc*:file=/var/log/app/gc.log \
  -jar app.jar

jcmd <pid> GC.heap_info          # current heap usage
jcmd <pid> GC.class_histogram    # object counts by class
jcmd <pid> GC.heap_dump /tmp/heap.hprof

Quick reference

  • HashMap: 16 buckets, load factor 0.75, index = hash & (n - 1), treeify at 8 when capacity is 64+
  • ConcurrentHashMap: lock-free reads, CAS into empty bins, synchronized on the bin head otherwise
  • volatile = visibility and ordering, not atomicity; use AtomicInteger or LongAdder for counters
  • Override equals and hashCode together; records generate both
  • G1 is the default GC since Java 9; Metaspace replaced PermGen in Java 8
  • @Transactional rolls back on unchecked exceptions by default; self-calls skip the proxy
  • Spring beans are singletons by default: no per-request state in fields

Common mistakes

  • Saying HashMap lookups are always O(1) without mentioning collisions.
  • Claiming volatile makes count++ safe.
  • Not knowing why @Transactional fails on private or self-invoked methods.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A HashMap with default settings has 12 entries. What happens when you add the 13th?

Question 2

2Why is count++ on a volatile int still unsafe across threads?

Question 3

3A @Transactional method throws a checked IOException. With default settings, what happens?

Question 4

4Which statement about ConcurrentHashMap iterators is true?

Question 5

5A Java service crashes with OutOfMemoryError: Metaspace. What is the most likely cause?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a final, immutable Money class with amount and currency, correct equals and hashCode, and a plus method that returns a new object.

  2. Exercise 2medium

    Count word frequencies from many threads into one shared map without losing updates and without a global lock.

  3. Exercise 3hard

    OrderService.placeOrder() calls this.saveAudit(), which is annotated @Transactional(propagation = REQUIRES_NEW), but the audit row is rolled back with the order. Explain why and fix it.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why is String immutable in Java?
Immutability makes strings safe to share between threads, lets the JVM reuse literals from the string pool, and lets String cache its hash code. It also stops a value like a file path from changing after a security check.
What is the difference between HashMap and Hashtable?
Hashtable is a legacy class where every method is synchronized and nulls are not allowed. HashMap is unsynchronised and allows one null key; for concurrency use ConcurrentHashMap instead of either.
Should I use virtual threads for everything now?
They are great for many blocking I/O tasks, such as one per HTTP request. They do not make CPU-heavy work faster, and you should still limit access to scarce resources like database connections.
What is the difference between @Component, @Service and @Repository?
All three register a bean. @Service and @Repository are specialisations that describe intent, and @Repository also enables translation of persistence exceptions into Spring's DataAccessException.
ShareXLinkedInWhatsApp