Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
How does Garbage Collection work in modern Java (G1GC vs. ZGC)?
senior LevelCode ExampleMemory Management
In Simple Words: Java GC automatically recovers heap memory allocated to unreferenced objects using mark-and-sweep and copying algorithms:
- G1GC (Garbage-First GC): The default collector since Java 9. Divides the heap into equal-sized regions (1MB to 32MB). It tracks region liveness and collects regions with the most garbage first to meet user-defined pause targets (
-XX:MaxGCPauseMillis=200). - ZGC (Z Garbage Collector): A low-latency, scalable collector in Java 17/21 designed for sub-millisecond pauses (
< 1ms) regardless of heap size (from megabytes to 16TB). It uses colored pointers and load barriers to perform concurrent marking, relocation, and compaction.
bash
# Production JVM Flags for Low-Latency Spring Boot microservices:
java -XX:+UseZGC -XX:+ZGenerational -Xms4g -Xmx4g -jar app.jar