Java Developer interview question
How does Java garbage collection affect an application?
Java GC reclaims objects no longer reachable from roots; allocation rate, heap sizing, object lifetime and collector choice affect throughput and pause time, so tune from GC logs and latency goals.
Direct answer
What a strong answer covers
How it works
The collector frees memory that is no longer reachable, and the application pays in two currencies: CPU spent tracing and copying objects, and pauses when the collector needs the application stopped. Young-generation collections are frequent and short; old-generation or full collections are rarer and longer. Allocation rate, the fraction of objects that survive, and heap size drive both. G1 balances throughput and pause time, ZGC and Shenandoah keep pauses in the millisecond range for large heaps at some throughput cost. Decisions come from GC logs and latency percentiles, not from folklore flags.
Example
A service with 200 ms p99 spikes every few minutes showed old-generation collections in the GC log caused by a cache that promoted millions of short-lived entries; bounding the cache and reducing allocation in the hot path removed the spikes without changing collector or heap size. Switching to ZGC would have hidden the symptom while the allocation problem stayed.
Common mistakes
- Setting a huge heap to reduce collections and getting longer pauses when they happen.
- Calling System.gc() from application code.
- Tuning flags copied from a blog post without reading the GC log of this workload.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.