Memory Management & Garbage Collection Questions
Memory as a performance resource in garbage-collected and managed runtimes (JVM, .NET, Go, V8, CPython). Covers allocation patterns and allocation pressure (boxing, value versus reference types, stack versus heap), GC algorithms and behaviour (generational, mark-and-sweep, reference counting, concurrent and compacting collectors, GC roots), pauses and tuning, heap sizing, fragmentation, object pooling and buffer reuse, data-oriented layouts and per-object overhead, on-heap versus off-heap trade-offs, and detecting and fixing memory leaks with heap dumps and profilers, including leaks from caches, closures, goroutines, asyncio tasks and native extensions. Emphasizes how memory pressure affects throughput, latency and stability, including low-latency and frame-rate-bound applications. Pointer, ownership and manual-allocation semantics, embedded memory budgets, virtual memory and paging, generic data-processing memory tricks, and GPU framework memory are covered elsewhere.
Describe a time you had to diagnose a memory leak in production. Explain your diagnostic steps (heap dumps, profilers, flame graphs), the root cause you found, the fix you deployed, and how you monitored to ensure the leak did not recur.
Sample Answer
Short answer. Tell it as one specific incident in the order situation, the actions you personally took, the root cause, the fix and its measured result, and the guard that stopped a repeat, and be honest about what you got wrong. The example below is a model you can adapt; replace every detail and number with your own, because an interviewer will probe them.
What a strong story contains
- Situation with a measurable symptom. Not "memory was high", but a number and a consequence.
- Your actions in sequence, with the tool and what each told you. "We looked at it" is weak; "I took two heap histograms ten minutes apart" is strong.
- A root cause stated precisely: which object, held by which reference, added by which change.
- The fix, plus how you proved it worked on the same metric that showed the problem.
- Prevention and a reflection: a detection gap closed, and one thing you would do differently.
Example answer (first person)
Situation. I was on call for a Java order-API service. After a Tuesday release its instances were being restarted by the orchestrator about every nine hours, and each restart dropped in-flight requests, which showed up as a burst of 5xx errors. The JVM heap was capped at 4 GB inside a 6 GB container, so the limit that was hit was the Java heap, not the kernel's container limit: the JVM threw OutOfMemoryError: Java heap space and the instance was restarted. On the dashboard, the heap after each full collection climbed from about 1.2 GB to the 4 GB ceiling over those nine hours. That is a rise of about 2.8 GB, roughly 310 MB per hour. A rising post-collection floor, as opposed to a rising raw number, is what told me this was a leak and not just a busy period.
Actions.
- Contained it. I did not start with the cause. We shortened the interval between planned rolling restarts to six hours (more frequent than the nine hours it took a leaking instance to run out), so each instance was restarted on our schedule before it reached the ceiling, which stopped the unplanned crashes and the 5xx bursts while I investigated.
- Narrowed it to one object type. On an instance I had taken out of the load balancer, I ran
jcmd <pid> GC.class_histogramtwice, ten minutes apart. One entry, a metrics class (Micrometer's timer, the object that records how long an operation took), had grown by tens of thousands of instances while everything else was flat. This histogram reports live objects by class, so growth in it is retention, not just allocation. - Found who was holding them. I took a heap dump with
jcmd <pid> GC.heap_dumpfrom that isolated instance (the jcmd docs list the impact as high and say it triggers a full collection unless-allis given, which is why I used an instance with no traffic) and opened it in Eclipse MAT, a heap-dump analyser. Its dominator tree lists objects by retained size, the memory that would be freed if that object disappeared (an object dominates another when every reference path from a GC root to the second goes through the first); it showed the metrics registry, the in-memory object that holds every meter the application has created, retaining most of the heap. "Path to GC roots" shows the chain of references that keeps one object alive, and it ended at the registry's internal map of meters. - Tied it to a code change. Reading the diff of the release, a new timer had been created with a tag built from the order ID. A tag is a label on a metric, and each distinct combination of metric name and tag values is its own meter series, which Micrometer keeps as a meter object in the registry for the life of the process. Cardinality is the number of distinct series, and an order ID has one value per order, so the cardinality grows without bound. In the dump those meters were all still registered and referenced by the registry, so every order added an entry that was never released. Micrometer's own documentation warns that tag values from user-supplied sources can blow up a metric's cardinality and should be bounded. The numbers fit: the service handled about 50 orders per second, which is 180,000 an hour and 30,000 new meters in each ten-minute histogram interval (the "tens of thousands" above), and 310 MB per hour divided by 180,000 orders is about 1.7 KB retained per order, a plausible size for a timer with its tags and registry entry. (These figures are illustrative; use your own.)
I should say that, after containing it and before the histogram in step 2, I spent a while on a flame graph (a chart of the call stacks sampled over time, where wider boxes mean more samples), and it did not help: an allocation flame graph shows where memory is allocated, which was a busy, unremarkable code path, not what stays retained. The histogram and the dominator tree were what answered the question.
Fix. I changed the tag to a bounded value (the order's status and the customer tier, a few dozen combinations at most) and moved the order ID to the log line, where it belongs. I also added a Micrometer meter filter (MeterFilter.maximumAllowableMetrics, which denies any meter after the registry reaches a set count) so a future mistake would be capped instead of fatal.
Result and monitoring. I deployed it to one canary instance first and watched the post-collection heap floor. It stayed near 1.3 GB over 72 hours of normal traffic where the old build would have crashed about eight times (72 hours / 9 hours per leak cycle) without our six-hour restarts. I then rolled it out and put the restart interval back to normal. To catch this class earlier I added an alert on the slope of the post-collection heap floor (not on the usage percentage) and a code-review checklist line: "does any new metric tag or map key have unbounded values?".
What I would do differently. The release had no soak test, so a nine-hour leak could not show in our twenty-minute pre-release load test. I proposed and later ran a four-hour soak stage on every release candidate. I would also have pulled the heap dump as soon as the rising floor appeared on the dashboard, which was hours before the first restart, instead of detouring through the flame graph.
Common mistakes when telling this story
- Claiming a result with no metric ("it got better").
- Saying "we" for every step so your own contribution is invisible.
- Naming tools without saying what each one told you.
- A neat story with no mistake in it, which reads as rehearsed.
- Skipping detection and prevention, and ending at "I fixed the bug".
If you have no production leak story
Use the closest real one (a staging or test-environment leak, a leak you found in a colleague's code review, or a memory problem in a side project) and say plainly where it ran. A smaller true story with real steps beats a large invented one.
Describe a thread-safe pool of reusable byte buffers for a hot loop. What should its API look like, how do you bound its size, and what can go wrong when pooling?
Sample Answer
Direct answer
Use a bounded queue of idle buffers and hand callers a lease object: acquire() takes an idle buffer or allocates a new one (it never blocks), and closing the lease returns the buffer if the queue has room, otherwise drops it for the garbage collector (GC). Bound the pool by capping idle buffers (here maxIdle), not by blocking callers, so a traffic spike degrades to ordinary allocation instead of stalling the hot loop. What goes wrong: a buffer returned twice and then handed to two threads, stale bytes from the previous user, buffers retained long after the load that justified them, and contention on the pool's own lock.
API and design
BufferPool(int bufferSize, int maxIdle)
Lease acquire() // idle buffer if available, else a fresh one; never blocks
byte[] Lease.bytes() // the buffer; throws once the lease is closed
void Lease.close() // idempotent; returns the buffer, or drops it if the pool is full
Design choices and why:
- Lease with
AutoCloseable:try (var lease = pool.acquire()) { ... }guarantees the return even on exceptions, and the lease nulls its own reference on close so a stale lease cannot touch a buffer that now belongs to someone else. ArrayBlockingQueuewithpollandoffer: a bounded, thread-safe queue whose non-blocking operations return immediately. Its capacity is the bound on idle memory: at mostmaxIdle x bufferSizebytes sit in the pool.- Idempotent close with a compare-and-set flag: idempotent means doing it twice has the same effect as doing it once.
compareAndSet(true, false)is an atomic (indivisible) instruction that flips the flag from true to false only if it is still true, and tells you whether it did. When two threads race, exactly one close succeeds, so a double close cannot enqueue the same array twice. - Counters (
created,reused,dropped) so you can see the hit rate in production.
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.LongAdder;
/** Bounded, thread-safe pool of fixed-size byte[] buffers. */
public final class BufferPool {
private final int bufferSize;
private final BlockingQueue<byte[]> idle; // never holds more than maxIdle buffers
private final LongAdder created = new LongAdder();
private final LongAdder reused = new LongAdder();
private final LongAdder dropped = new LongAdder();
public BufferPool(int bufferSize, int maxIdle) {
this.bufferSize = bufferSize;
this.idle = new ArrayBlockingQueue<>(maxIdle);
}
/** Never blocks: if no idle buffer exists, allocate a fresh one. */
public Lease acquire() {
byte[] b = idle.poll();
if (b == null) { created.increment(); b = new byte[bufferSize]; }
else reused.increment();
return new Lease(b);
}
public final class Lease implements AutoCloseable {
private byte[] buf;
private final AtomicBoolean open = new AtomicBoolean(true);
private Lease(byte[] buf) { this.buf = buf; }
public byte[] bytes() {
if (!open.get()) throw new IllegalStateException("lease already closed");
return buf;
}
/** Idempotent: a second close() cannot put the same array in the pool twice. */
@Override public void close() {
if (open.compareAndSet(true, false)) {
byte[] b = buf;
buf = null; // the lease no longer references it
if (!idle.offer(b)) dropped.increment(); // pool full: let the GC have it
}
}
}
public long acquires() { return created.sum() + reused.sum(); }
public String stats() {
return "created=" + created.sum() + " reused=" + reused.sum() + " dropped=" + dropped.sum() + " idle=" + idle.size();
}
// ---- driver ----
public static void main(String[] args) throws Exception {
// 1. Bound: 100 simultaneous leases, pool allows 4 idle.
BufferPool p = new BufferPool(1024, 4);
Lease[] held = new Lease[100];
for (int i = 0; i < 100; i++) held[i] = p.acquire();
for (Lease l : held) l.close();
held[0].close(); // double close is harmless
System.out.println("bound: " + p.stats());
// 2. Stale data: a buffer comes back with the previous user's bytes.
BufferPool q = new BufferPool(16, 2);
try (Lease a = q.acquire()) { a.bytes()[0] = 42; }
try (Lease b = q.acquire()) { System.out.println("stale byte: " + b.bytes()[0]); }
// 3. Concurrency: 8 threads, each stamps its buffer, yields, and checks nobody else touched it.
BufferPool c = new BufferPool(4096, 16);
int threads = 8, iterations = 200_000;
LongAdder corrupted = new LongAdder();
Thread[] ts = new Thread[threads];
for (int t = 0; t < threads; t++) {
final byte stamp = (byte) (t + 1);
ts[t] = new Thread(() -> {
for (int i = 0; i < iterations; i++) {
try (Lease l = c.acquire()) {
byte[] b = l.bytes();
java.util.Arrays.fill(b, stamp);
if ((i & 1023) == 0) Thread.yield();
for (int k = 0; k < b.length; k += 512) if (b[k] != stamp) { corrupted.increment(); break; }
}
}
});
ts[t].start();
}
for (Thread t : ts) t.join();
System.out.println("concurrent: acquires=" + c.acquires() + " corrupted=" + corrupted.sum()
+ " idle<=16: " + (c.stats().contains("idle=") && c.idle.size() <= 16));
}
}
Compiled with javac -Xlint:all BufferPool.java (no warnings) and run with java BufferPool on JDK 21 (Temurin 21.0.12), it prints the same three lines on every run, because the concurrent part prints only a total and a count that must be zero:
bound: created=100 reused=0 dropped=96 idle=4
stale byte: 42
concurrent: acquires=1600000 corrupted=0 idle<=16: true
What the driver does: part 1 holds 100 leases open at once, closes them all, then closes held[0] a second time to prove the double close is harmless. Part 2 writes 42 into a buffer, returns it, and reads the next buffer acquired (which is the same array) to expose the leftover byte. Part 3 gives each of 8 threads its own stamp value, fills its whole buffer with that stamp, and later re-reads the buffer; if the pool ever handed one array to two threads, one thread's fill would overwrite the other's stamp and the check would see a foreign value. Thread.yield() every 1,024th iteration pauses a thread while it still holds its lease, which gives other threads a chance to run during that window and makes a sharing bug more likely to show. Checking every 512th index (8 positions of a 4,096-byte buffer) is enough because the fill writes the whole array, and it keeps the check cheap.
Reading the three lines:
- Bound: 100 leases were open at once, so 100 buffers were created. Closing them all kept only 4 (the cap) and dropped 96. The second
close()on one lease changed nothing: 100 - 4 = 96 dropped, not 97. - Stale data: the next user of a returned buffer saw the previous user's byte (42). A pool does not clear buffers, because zeroing costs time on every release. If buffers can carry sensitive data or if code assumes zeroed memory, clear on release (
Arrays.fill), or track a valid length and never read past it. - Concurrency check: 8 threads made 8 x 200,000 = 1,600,000 acquisitions; each thread stamped its buffer with its own value and checked it back, and no buffer was ever seen with another thread's stamp. The exact
createdandreusedcounts vary from run to run, so the check prints only their total. To confirm the harness can fail, changeidle.poll()inacquire()toidle.peek(): that hands the same idle array to many callers without removing it from the queue, and the same driver then reports a large nonzerocorruptedcount (hundreds of thousands of the 1,600,000 acquisitions; the exact figure changes on every run).
Complexity and cost
acquire and close are O(1). Idle memory is bounded by maxIdle x bufferSize (for example 16 x 4,096 = 65,536 bytes). Memory in flight is not bounded by the pool, because acquire never blocks; if you need a hard cap on total buffers, add a counting semaphore around acquire, at the price of callers waiting.
What can go wrong when pooling
- Double release or use after release: two threads share one buffer and silently corrupt each other's data. The lease, the idempotent close and the nulled reference are the defence; a bare
release(byte[])method offers none. - Stale state: shown above. Treat buffer contents as undefined on acquire.
- Retention and the generational collector: retention means holding memory after the work that needed it is over. Pooled buffers live long, so they are copied into the old generation, where they are reclaimed only by the rarer, more expensive old-generation work (full collections, or G1's mixed collections that include old regions), while a short-lived young
byte[]is nearly free to allocate and discard. If the pool holds more than the load needs, you pay memory for nothing. A pool must also not retain references that prevent reclamation: this one holds onlybyte[], which has no references inside, and the lease drops its pointer on close. A pool of objects with fields must null or reset those fields on release, otherwise an idle pooled object keeps its referents alive. - Contention: the queue uses an internal lock, and contention means threads queuing up to take that one lock. At high thread counts that lock becomes the bottleneck and can cost more than the allocations it saves; use per-thread caches (a small pool per worker) with a shared overflow.
- Sizing wrong:
maxIdlebelow peak concurrency means constant allocation plus drops; far above it means retained memory. Start near the number of worker threads and use thecreatedanddroppedcounters to adjust.
Recommendation and what would flip it
Pool only when a profile shows large or frequent buffers causing GC cost; for small, short-lived buffers allocating fresh is usually cheaper and safer in a generational collector. Keep the non-blocking design unless you must cap total memory; then add a semaphore. Switch to per-thread pools when the lock shows up in a profile.
Write a short Python example that creates a reference cycle preventing GC (e.g., two objects referencing each other and defining del), then show how to fix it so CPython's garbage collector can reclaim them. Explain why del complicates cycle collection.
Sample Answer
Short answer: CPython frees most objects with reference counting (each object counts how many references point at it and is freed the instant the count hits zero). A reference cycle keeps every member's count above zero, so counting alone can never free it. A second mechanism, the cyclic garbage collector, finds unreachable cycles. The part of the premise to correct: since Python 3.4 (PEP 442), an object with __del__ inside a cycle is NOT stuck forever. Before 3.4 it was.
The demo (Python 3.12, run in a container). The collector is switched off so only the explicit gc.collect() calls run:
import gc
import weakref
class Node:
"""Holds a strong reference to a peer and announces its own cleanup."""
def __init__(self, name):
self.name = name
self.peer = None
def __del__(self):
print(f" __del__ ran for {self.name}")
def make_strong_cycle():
a, b = Node("a"), Node("b")
a.peer = b
b.peer = a # a -> b -> a : reference cycle
# a and b go out of scope here, but each is still referenced by the other
class WeakNode(Node):
"""Same class, but the back-pointer is a weak reference."""
def set_peer_weak(self, other):
self.peer = weakref.ref(other)
def make_broken_cycle():
a, b = WeakNode("wa"), WeakNode("wb")
a.peer = b # strong: a keeps b alive
b.set_peer_weak(a) # weak: b does not keep a alive
# when the function returns, refcount of a drops to 0 immediately
gc.disable() # make the demo deterministic: only our explicit collects run
print("strong cycle, then function returns:")
make_strong_cycle()
print(" (nothing printed: refcounts never reached zero)")
print("gc.collect() ->", gc.collect(), "unreachable objects found")
print("gc.garbage ->", gc.garbage)
print("\nweakref back-pointer, then function returns:")
make_broken_cycle()
print("gc.collect() ->", gc.collect(), "(already freed by refcounting)")
Output on python:3.12-slim (Python 3.12.15):
strong cycle, then function returns:
(nothing printed: refcounts never reached zero)
__del__ ran for a
__del__ ran for b
gc.collect() -> 2 unreachable objects found
gc.garbage -> []
weakref back-pointer, then function returns:
__del__ ran for wa
__del__ ran for wb
gc.collect() -> 0 (already freed by refcounting)
(The count is the two nodes. In a fresh interpreter the first gc.collect() can report a larger number, because it counts every unreachable object it finds, including unrelated interpreter start-up objects that were already waiting; the extras are not part of the demo. Treat any figure above 2 as incidental.)
Reading it.
- After
make_strong_cyclereturns, nothing outside can reachaorb, buta.peerpoints atbandb.peerpoints ata. Both counts stay at 1, so refcounting frees nothing and the__del__lines do not appear. In a service this is a slow leak until the collector runs. gc.collect()found the cycle, ran both finalizers, and freed the objects. The two__del__lines appear above thegc.collect() ->line, and not insidemake_strong_cycle, because Python evaluates every argument of aprint(...)call before printing anything:gc.collect()runs first (printing the finalizer lines as it frees the nodes), and only then doesprintwritegc.collect() -> 2 ....gc.garbageis empty. Thegcdocs say that since 3.4 this list "should be empty most of the time, except when using instances of C extension types with a non-NULLtp_delslot". (A C extension type is a class implemented in C rather than Python, as innumpyorsqlite3;tp_delis the old C-level finalizer hook those types could still use, which the collector cannot safely call in a cycle.)- In the fixed version the back-pointer is a
weakref.ref(a reference that does not raise the target's count). Nothing is a cycle in terms of counts: when the function returns,wadrops to zero, is freed at once and releaseswb. Deterministic, no collector needed.
Why __del__ used to complicate cycle collection. A finalizer (__del__) is code that runs just before an object's memory is released, and it can touch the object's attributes, including other objects in the cycle. In a cycle the collector has no safe order: running a.__del__ may use b, and b may already be half torn down. Before Python 3.4 the collector refused to guess, skipped such cycles and parked the objects in gc.garbage, so they leaked until you broke the cycle by hand. PEP 442 ("Safe object finalization") changed this: the collector now calls the finalizers on the whole unreachable group first, then re-checks that nothing was resurrected (a finalizer storing self somewhere reachable), and only then clears references and frees. The remaining uncollectable case is C extension types that still use the legacy tp_del slot.
Residual hazards even on modern Python.
- Finalizer order inside a cycle is not defined, so
__del__must not assume its peers are intact. __del__can run late, on whichever thread triggers the collection, or at interpreter shutdown. Do not use it to release locks, sockets or files. Usewith/contextlib/weakref.finalizefor that.- Exceptions raised in
__del__are printed and ignored, never propagated.
Fix options, in the order I would reach for them. (1) Remove the cycle by design: make the child-to-parent link a weakref, as above. (2) Provide an explicit close() and use a context manager so cleanup does not depend on the collector. (3) Break the cycle manually (a.peer = None) before dropping the objects. Calling gc.collect() on a timer is a diagnostic, not a design: it pauses the process (it examines every tracked object in the generations it collects).
To prove a cycle leak in a real service: set gc.set_debug(gc.DEBUG_SAVEALL) in a test, call gc.collect(), and inspect gc.garbage for what the collector found unreachable.
Compare an object-per-record design with a data-oriented layout for processing millions of small records in memory. How does each affect allocation rate, cache behaviour and GC cost?
Sample Answer
The two designs. Object-per-record means each record is its own heap object (a class Order with id, price, qty), and your collection is an array of references to them. Data-oriented layout (also called structure of arrays, as opposed to the array of structures that object-per-record gives you) means one primitive array per field: int[] id, double[] price, int[] qty, and record i is index i in each. Same data, different memory shape.
Where the cost of object-per-record comes from (JVM numbers). Every Java object carries a header (the runtime's bookkeeping: type pointer plus GC and lock bits), and sizes round up to a multiple of 8 bytes. With compressed object pointers (the JVM stores each reference in 4 bytes instead of 8, which is the default for heaps under about 32 GB) one Order is 12 bytes of header + 4 (int) + 8 (double) + 4 (int) = 28, rounded to 32 bytes, plus a 4-byte reference slot in the array: 36 bytes per record against 16 bytes of real data in the column layout. For 5 million records: 5,000,000 x 36 = 180 MB (about 172 MiB) vs 5,000,000 x 16 = 80 MB (about 76 MiB). That is 2.25x before any GC overhead, and the header ratio is worse for smaller records. The measured heap growth below matches for the object layout (172 MiB against an estimate of 171.7) and lands about 3 MiB above the estimate for the columns (79 MiB against 76.3). The gap is G1's region accounting: with a 2 GiB heap G1 uses 1 MiB regions, and an array larger than half a region is a humongous object that occupies whole regions. The double[] of 38.15 MiB takes 39 regions and each int[] of 19.07 MiB takes 20, which is 39 + 20 + 20 = 79 MiB. Setting -XX:G1HeapRegionSize=32m moves the column figure well above 100 MiB, which shows the accounting, not the data, is what moves. The used-heap figures are therefore specific to G1 and this region size; other collectors report different totals for the same data.
Measured (JDK 21 container on an arm64 laptop, G1, -Xms2g -Xmx2g, 5 million records, each layout in its own JVM so one cannot disturb the other; this is a plain System.nanoTime harness, not JMH, so read the ratios, not the milliseconds). The heap figures and GC counts are essentially fixed (the object layout's live-heap figure moved by 1 MiB on an occasional re-run); the timings vary from run to run and machine to machine, so the lines below are one run and the ranges over repeated re-runs follow them:
object-per-record: live heap +172 MiB, 1 GCs while building, sequential scan 3 ms, random-order scan 61 ms, full GC 11 ms
column arrays: live heap +79 MiB, 0 GCs while building, sequential scan 3 ms, random-order scan 45 ms, full GC 2 ms
(The block above is from a 14-CPU container. Across repeated runs the sequential scan was a near tie and the random-order scan was consistently slower for the object layout by a modest margin. The full-GC time depends strongly on the CPU count, because the collector marks with parallel worker threads: the same program in containers limited to two CPUs, and then to one, took several times longer for the object layout's full GC, while the column layout's stayed at a millisecond or two. The live-heap figures and the GC counts did not change with the CPU count.) Two details of the program: usedMiB calls System.gc() twice so that garbage left over from the work just done is collected before the heap is read, which makes the before and after readings comparable; and the order array is a seeded shuffle of the indexes 0 to N - 1, a random visiting order that defeats the hardware prefetcher and is identical for both layouts. The program, run as javac RecordLayoutDemo.java && java -XX:+UseG1GC -Xms2g -Xmx2g RecordLayoutDemo objects and again with columns:
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Random;
public class RecordLayoutDemo {
static final int N = 5_000_000;
static final class Order { // object-per-record layout
final int id;
final double price;
final int qty;
Order(int id, double price, int qty) { this.id = id; this.price = price; this.qty = qty; }
}
static long gcCount() {
return ManagementFactory.getGarbageCollectorMXBeans().stream().mapToLong(GarbageCollectorMXBean::getCollectionCount).sum();
}
static long usedMiB() {
System.gc();
System.gc();
Runtime rt = Runtime.getRuntime();
return (rt.totalMemory() - rt.freeMemory()) >> 20;
}
static volatile double sink;
static long medianMs(Runnable r) {
long[] t = new long[9];
for (int i = 0; i < t.length; i++) {
long t0 = System.nanoTime();
r.run();
t[i] = (System.nanoTime() - t0) / 1_000_000;
}
Arrays.sort(t);
return t[t.length / 2];
}
static long fullGcMs() {
long[] t = new long[5];
for (int i = 0; i < t.length; i++) {
long t0 = System.nanoTime();
System.gc();
t[i] = (System.nanoTime() - t0) / 1_000_000;
}
Arrays.sort(t);
return t[t.length / 2];
}
public static void main(String[] args) {
String mode = args[0];
int[] order = new int[N]; // random visiting order, same for both layouts
for (int i = 0; i < N; i++) order[i] = i;
Random rnd = new Random(42);
for (int i = N - 1; i > 0; i--) { int j = rnd.nextInt(i + 1); int t = order[i]; order[i] = order[j]; order[j] = t; }
long base = usedMiB();
long g0 = gcCount();
long seqMs, randMs, liveMiB;
if (mode.equals("objects")) {
Order[] orders = new Order[N];
for (int i = 0; i < N; i++) orders[i] = new Order(i, i * 0.01, i % 7 + 1);
long gcs = gcCount() - g0;
liveMiB = usedMiB() - base;
seqMs = medianMs(() -> { double s = 0; for (Order o : orders) s += o.price * o.qty; sink = s; });
randMs = medianMs(() -> { double s = 0; for (int i : order) { Order o = orders[i]; s += o.price * o.qty; } sink = s; });
System.out.printf("object-per-record: live heap +%d MiB, %d GCs while building, sequential scan %d ms, random-order scan %d ms, full GC %d ms%n", liveMiB, gcs, seqMs, randMs, fullGcMs());
} else {
double[] price = new double[N];
int[] qty = new int[N];
int[] id = new int[N];
for (int i = 0; i < N; i++) { id[i] = i; price[i] = i * 0.01; qty[i] = i % 7 + 1; }
long gcs = gcCount() - g0;
liveMiB = usedMiB() - base;
seqMs = medianMs(() -> { double s = 0; for (int i = 0; i < N; i++) s += price[i] * qty[i]; sink = s; });
randMs = medianMs(() -> { double s = 0; for (int i : order) s += price[i] * qty[i]; sink = s; });
System.out.printf("column arrays: live heap +%d MiB, %d GCs while building, sequential scan %d ms, random-order scan %d ms, full GC %d ms%n", liveMiB, gcs, seqMs, randMs, fullGcMs());
if (id[N - 1] != N - 1) System.out.println("unreachable");
}
}
}
Reading the numbers, one effect at a time.
- Allocation rate. Building the object layout makes 5 million small allocations (5,000,000 x 32 bytes = 160 MB through the young generation) and triggered a collection; the column layout makes three array allocations and no collection. In a service that rebuilds such data per request, per-record allocation is what sets how often young collections run, and their CPU time is taken from request handling.
- GC cost. A tracing collector pays per live object when it marks: 5 million objects plus an array of 5 million references to follow, versus three arrays of primitives that contain no references, so the collector does not look inside them. The full-GC times printed above (11 ms against 2 ms, from a 14-CPU container) point the same way, and the gap widens when fewer CPUs share the marking work. Records that die young are cheap for a generational collector, but records that live for minutes get copied between generations and re-marked.
- Cache behaviour depends on the access pattern. A sequential scan was a near tie (3 ms vs 3 ms in the block above) because objects allocated in a loop sit next to each other and the hardware prefetcher (it fetches upcoming cache lines before you ask) hides the header overhead. In random order the object layout was slower, 61 ms against 45 ms in the block above (a modest gap, well under 2x at this size). A cache line is the 64-byte block the CPU fetches from memory at a time: touching one byte of a record pulls in its whole line. In this scan a random visit costs about two line fetches in either layout (objects: the reference slot in the array, then the
Orderitself, which is 32 bytes, so half of its line belongs to a neighbour; columns: one line inprice, one inqty), so the line count alone does not explain the gap. Footprint (172 against 79 MiB) does not explain it alone either: re-running the same program with the record count changed (the constant is replaced bystatic final int N = Integer.getInteger("n", 5_000_000);and the program is run with-Dn=1500000or-Dn=3000000) kept the footprint ratio near 2.2x at every size, yet the random-order gap was about 3x at 1.5 million records and clearly smaller at 3 million and smaller again at 5 million, where both layouts are probably bound by main-memory latency. A plausible extra contributor is that the object layout's two reads are dependent (the address of theOrdercomes from the array slot, so the second miss cannot start until the first returns) while the two column reads are independent and can overlap; this program does not isolate that, so treat it as a hypothesis. Columns win most when a loop reads only some fields (a sum ofprice * qtynever touchesid, and a loop overpricealone touches one line per record) and lose their edge when every access needs all three fields: three arrays then cost three line fetches per record against two for the object layout.
Trade-offs, and what I would do. Columns cost you convenience: no per-record identity, no polymorphism, more index bookkeeping, and mutation that must keep arrays in step. Objects keep the code simple and are fine up to hundreds of thousands of records. My recommendation: keep objects for domain logic and switch to columns (or a packed ByteBuffer or memory segment) only for the large, read-mostly hot set, once an allocation profile or GC log shows record objects dominate allocation rate or the old generation, which happens at millions of records. Game engines make the same trade with entity-component systems (an architecture in which each kind of data, such as position or health, is stored in its own contiguous array and entities are just indexes into them). What would flip it: if records are short-lived, the young-generation collector discards them cheaply and the object layout can be fine; if the set is long-lived and huge, columns win on footprint and GC time.
An object you expected to be collected is still alive. Explain what GC roots are, and describe how long-lived caches, static or module-level variables, and captured closures can keep objects reachable. How would you confirm and fix it?
Sample Answer
Short answer. GC roots are the references the running program holds directly, the starting points of every reachability trace: local variables and parameters on each live thread's stack, static fields, references from native code, and the threads themselves. An object stays alive if any chain of references leads from a root to it. Caches, statics and captured closures keep objects alive because each one hangs the object off a long-lived root.
How each one pins objects
- Long-lived cache. A
static Mapor a singleton cache is a root. Everything put in it stays until someone removes it. Without an eviction rule it only grows. - Static or module-level variable. Reachable for the life of the class loader (the JVM component that loads classes; a class and its static fields live as long as its loader, usually the whole process) or process. A static list of "recent requests" holds every request object, and everything those objects reference, forever.
- Captured closure. A lambda or inner function keeps a reference to everything it captures, including the enclosing object (
this). Hand a lambda to a long-lived registry and you hand over the whole enclosing object, even if the lambda body uses one field. The thread-local case is similar: a pooled thread is itself a root, so values in its thread-local map stay until removed.
Demonstration
A weak reference is a reference that does not keep its target alive: if only weak references point to an object, the collector may reclaim it, and the weak reference then reads as empty (get() returns null). That makes it a probe for "is this object still held by something else?". A screen object owns a 4 MB buffer and registers a listener lambda in a static list:
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.function.Consumer;
public class ListenerRootsDemo {
static final List<Consumer<String>> LISTENERS = new ArrayList<>(); // static: a GC root
static class Screen {
final byte[] bigBuffer = new byte[4 * 1024 * 1024];
void register() {
LISTENERS.add(msg -> use(bigBuffer, msg)); // lambda captures this (the Screen)
}
static void use(byte[] b, String m) { }
}
static boolean collected(WeakReference<Screen> ref) {
for (int i = 0; i < 5 && ref.get() != null; i++) { System.gc(); }
return ref.get() == null;
}
public static void main(String[] args) {
Screen a = new Screen();
a.register();
WeakReference<Screen> ref = new WeakReference<>(a);
a = null; // no local variable points at it any more
System.out.println("after dropping local, collected? " + collected(ref));
LISTENERS.clear(); // remove the root path
System.out.println("after removing listener, collected? " + collected(ref));
}
}
Run with java -Xmx256m ListenerRootsDemo.java on eclipse-temurin:21-jdk (OpenJDK 21.0.12):
after dropping local, collected? false
after removing listener, collected? true
Setting the local variable to null did nothing: the static LISTENERS list still reached the lambda, and the lambda reached the screen and its buffer. Removing the listener cut the last root path, and the weak reference then cleared. (System.gc() is only a request that HotSpot honours by default; the demo uses it to make the outcome visible, and a service should not depend on it.)
The module-level case works the same way in Python. A list at module scope is a root for the life of the process, and CPython (the standard interpreter) frees an object when nothing references it:
import gc
import weakref
RECENT = [] # module-level list: lives as long as the process
class Session:
def __init__(self):
self.data = bytearray(1_000_000)
def handle():
s = Session()
RECENT.append(s) # "remember the last requests" and never trim
return weakref.ref(s) # a weak reference does not keep s alive
ref = handle()
gc.collect()
print("after the function returned, still alive?", ref() is not None)
RECENT.clear()
gc.collect()
print("after clearing the list, still alive?", ref() is not None)
Run with python -I module_pin.py on python:3.12-slim (Python 3.12.15):
after the function returned, still alive? True
after clearing the list, still alive? False
handle() returned and its local s is gone, yet the Session survives because RECENT still lists it; weakref.ref is Python's weak reference, so ref() returns the object while it lives and None once it is freed.
Confirm it
- Name the suspect class with a class histogram (
jcmd <pid> GC.class_histogram) or from a heap dump, filtered to the object you expected to be gone. - Get the reference chain. Open the heap dump in an analyzer such as Eclipse MAT and run "path to GC roots" on one suspect instance, excluding weak and soft references from the path (those references do not keep an object alive, so the paths that remain are the ones that actually pin it). JFR can also capture the chain: the JDK troubleshooting guide uses
jcmd <pid> JFR.dump ... path-to-gc-roots=truewith theOldObjectSampleevent (a JFR event that samples long-lived objects and, with that option, records the path from a GC root to each). - Read the chain bottom-up. It will end at a static field, a thread, or a registry, with a lambda or another captured reference in the middle. That chain, not the leaked object, is where the bug is.
- Test the hypothesis cheaply. In a test or a debug endpoint, remove the suspected registration or clear the suspected cache, force a collection, and check whether the weak reference (as in the demo) or instance count drops.
Fix
Match the fix to the root: bound or expire the cache; unregister listeners in the lifecycle's teardown method; hold a long-lived registry's entries through weak references when the registrant should control lifetime (WeakReference, WeakHashMap, or a weak-value cache); avoid capturing the enclosing object by extracting what the closure needs into a local; clear thread-locals in pooled threads in a finally. Verify with the same load: post-collection heap floor stays flat, instance count for the suspect class stops growing.
Unlock Full Question Bank
Get access to all 24 Memory Management & Garbage Collection interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.