Java Backend Interview Q&A← All stacks

Memory Model & Garbage Collection — Interview Q&A Matrix

Parent stack: Core Java Runtime Technology: Memory Model & Garbage Collection Levels: Senior Questions: 2

Each entry contains a Question, the Expected Depth, an Ideal Answer, and Red Flags.

Senior

Q1 — The Java Memory Model, volatile, and happens-before

Question: A worker thread does not see an updated running flag and continues to loop. Explain the Java Memory Model issue and fix it.

java
class Worker implements Runnable {
    private boolean running = true;

    public void stop() { running = false; }

    public void run() { while (running) { /* work */ } }
}

Expected Depth:

Ideal Answer:

java
class Worker implements Runnable {
    private volatile boolean running = true;

    public void stop() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            doWork();
        }
    }
}
java
private final AtomicLong count = new AtomicLong();

count.incrementAndGet();
java
private final ReentrantLock lock = new ReentrantLock();
private long debit;
private long credit;

void transfer(long amount) {
    lock.lock();
    try {
        debit -= amount;
        credit += amount;
    } finally {
        lock.unlock();
    }
}

Red Flags:


Q2 — Garbage collection and tuning (G1 vs ZGC)

Question: A service has regular latency spikes that occur during GC pauses. How would you diagnose and reduce them on Java 17 or Java 21?

Expected Depth:

Ideal Answer:

bash
-Xlog:gc*,safepoint:file=gc.log:time,uptime,level,tags
bash
-XX:+UseG1GC -Xms4g -Xmx4g -XX:MaxGCPauseMillis=200
bash
-XX:+UseZGC -XX:+ZGenerational -Xms4g -Xmx4g
bash
-XX:+UseShenandoahGC -Xms4g -Xmx4g

Red Flags:


Scoring Rubric

Level Pass bar
JuniorExplains basic memory and GC concepts correctly.
SeniorUses evidence to diagnose visibility and GC problems and explains the trade-offs.
ArchitectDefines safe memory and GC standards and validates them under realistic load.