Java Garbage Collection Explained: JVM Memory, Algorithms, GC Types and Tuning
Java garbage collection automatically reclaims heap memory that is no longer reachable from live JVM roots. Use this guide to understand the mechanism, memory areas, G1 and ZGC internals, collector trade-offs, diagnostic commands, experienced interview questions and Minecraft-specific decisions.
Quick Answer: What Does Java Garbage Collection Do?
The JVM identifies heap objects that cannot be reached from active roots, preserves reachable objects, reclaims unreachable memory and may move live objects to create usable free space. The collection time is adaptive—not daily, weekly or tied to a fixed Java schedule.
Unreachable means collectible
An object becomes eligible when no live reference path from a GC root reaches it.
GC is demand-driven
Allocation pressure, generation occupancy, collector policy and failed allocations influence when work begins.
Some coordination still pauses threads
Concurrent collectors reduce pause work, but current general-purpose collectors still require brief stop-the-world phases.
GC cannot remove reachable leaks
An unbounded cache, static map, queue or listener can keep unwanted objects alive indefinitely.
Run a supported JDK, keep rotating GC logs enabled, measure pause latency and throughput, and change a collector or flag only when evidence identifies a specific problem.
📅 Which Week Am I On? — Garbage or Recycling?
160+ Canadian cities · CSS animated bins · Monthly calendar · Holiday warnings
City not in our database yet
We don't have a reference date for this city. To find your biweekly schedule, use one of these options:
Once you have the date of your last garbage week, enter it in the date field above and click Check.
Next pickup date
Based on your collection day
🔑 Bookmark this page to check your schedule every 2 weeks
The Java Memory Model defines thread visibility, ordering and synchronization. Heap, stacks, Metaspace, code cache and native allocations are runtime memory areas.
Java 26 Version Check: Defaults and Changes That Affect GC Advice
Garbage-collection advice must name the JDK version and distribution. A valid Java 8 flag set, CMS explanation or older ZGC mode may be wrong for Java 26.
Java 26 can test -XX:+UseCompactObjectHeaders to reduce ordinary 64-bit object headers to 64 bits. Validate framework compatibility, class-loading scale and real memory savings before production use.
Java Garbage Collection and Memory Management
GC mainly manages Java heap objects. A complete memory investigation must also include stacks, class metadata, compiled code, direct buffers, JNI memory and collector bookkeeping.
OutOfMemoryError: Java heap space, rising live set or long collection cycles.StackOverflowError or failure to create additional native threads.OutOfMemoryError: Metaspace.-Xmx- Unreachable Java objects and arrays.
- Unused classes after their defining class loader is collectible.
- Regions or generations containing reclaimable heap space.
- Objects handled through soft, weak and phantom reachability rules.
- Reachable objects retained by application logic.
- Files, sockets and database resources left open.
- Native leaks inside JNI or third-party libraries.
- Excessive thread count and stack consumption.
- A container limit with insufficient native headroom.
Java Garbage Collection Diagram: Roots, Generations and G1 Regions
These original diagrams show the core reasoning. Exact allocation paths, object movement and pause phases depend on the selected collector.
active local references
loaded classes
native references
runtime roots
Conceptual G1 heap layout
Eden region for newer allocations.
Survivor region for young objects that remain reachable.
Old region containing longer-lived objects.
Humongous object spanning one or more old-generation regions.
Java Garbage Collection Mechanism in Depth
The application allocates objects
Most normal objects use a fast young-generation allocation path. Collector-specific large objects can bypass the ordinary young path.
A collector trigger is reached
Young space can fill, old occupancy can cross a threshold, an allocation can fail or metadata pressure can require cleanup.
The JVM coordinates application threads
Some phases bring threads to a safepoint. Concurrent collectors move a larger share of marking or relocation beside application execution.
GC roots are scanned
The collector starts from thread stacks, static fields, JNI handles and JVM structures, then traces the reachable object graph.
Cross-generation references are included
Card tables, write barriers and remembered sets prevent the collector from missing references from one region or generation into another.
Reference objects are processed
Soft, weak and phantom references follow weaker reachability rules than normal strong references and can interact with reference queues.
Memory is reclaimed or evacuated
The collector may sweep dead blocks, copy live objects, compact memory or reclaim entire source regions after evacuation.
Application execution continues
Paused threads resume. A concurrent collector may continue marking, remapping, relocating or cleaning until the cycle finishes.
System.gc() does not provide deterministic memory control
It requests collection. HotSpot can execute an expensive collection, process it differently according to the collector or ignore explicit requests when explicit GC is disabled.
Java Garbage Collection Algorithms vs Collector Types
Marking, sweeping, copying and compaction are algorithmic building blocks. G1, ZGC, Parallel and Serial are complete collectors that combine those techniques with different concurrency and pause strategies.
Collectors use different phase names and scopes. Diagnose the collector, event cause, phase, pause duration and before/after occupancy instead of relying only on one generic event name.
Java Garbage Collection Types: Serial, Parallel, G1, ZGC and Shenandoah
-XX:+UseSerialGC-XX:+UseParallelGC-XX:+UseG1GC-XX:+UseZGC-XX:+UseShenandoahGCStart with the supported JDK’s default collector. Switch only after realistic testing shows that another collector better meets the application’s latency, throughput and footprint goals.
Java Garbage Collector Decision Helper
This helper suggests a collector to test first. It does not replace production logs, a realistic load test or the selected JDK’s support matrix.
G1 Garbage Collection in Depth
G1 divides the heap into equally sized regions and assigns those regions dynamically to young, survivor, old, free or humongous roles. It incrementally reclaims old memory instead of depending only on a monolithic whole-heap cleanup.
Frequent young collections
Eden and survivor regions are processed while old occupancy gradually approaches the concurrent-marking threshold.
Estimate old-region liveness
G1 discovers how much live data remains in old regions while performing much of the work beside the application.
Young plus selected old regions
G1 adds efficient old regions to later collection sets and evacuates live objects out of them.
Special old-region allocation
An object at least half the G1 region size receives humongous treatment and can span multiple contiguous regions.
Common G1 log signals
-XX:MaxGCPauseMillis is a target—not a guarantee
G1 adapts young-generation sizing and collection work to pursue the target. Setting an unrealistically low value can increase collection frequency and reduce throughput.
Oracle recommends allowing G1 to resize young memory to meet pause goals. Options that pin young-generation size can undermine this adaptive control.
ZGC in Depth: Low Pauses, Heap Headroom and Allocation Stalls
ZGC is designed for very low latency and performs expensive collection work concurrently. Oracle’s Java 26 guide describes maximum pauses under one millisecond, independent of the heap size being used, with supported heap scales from a few hundred megabytes to 16 TB.
Sub-millisecond maximum target
ZGC minimizes stop-the-world work so pause duration is not proportional to the live heap size.
Provide enough maximum heap
ZGC needs space for the application’s live set and allocations that continue while concurrent collection is running.
Latency can cost throughput
Concurrent marking and relocation consume processor resources and require sufficient CPU scheduling.
What SoftMaxHeapSize changes
-XX:SoftMaxHeapSize gives ZGC a softer operational target below -Xmx. ZGC can exceed the soft target when necessary to avoid an allocation stall or out-of-memory condition, while the hard maximum remains -Xmx.
java \
-Xms2g \
-Xmx5g \
-XX:+UseZGC \
-XX:SoftMaxHeapSize=4g \
-Xlog:gc*,safepoint:file=logs/zgc.log:time,uptime,level,tags:filecount=5,filesize=20M \
-jar app.jar
Investigate allocation rate, available heap headroom, CPU throttling, live-set size and workload bursts before treating an additional ZGC flag as the primary fix.
Java GC Logs, JFR, Heap Dumps and Native Memory Tracking
GC logs explain collection events. Java Flight Recorder connects GC with allocations, threads, CPU, locks and application activity. Heap dumps identify retained objects, while Native Memory Tracking accounts for JVM-internal native allocations.
Java 9+ production logging baseline
java \
-Xms2g \
-Xmx2g \
-Xlog:gc*,safepoint:file=logs/gc.log:time,uptime,level,tags:filecount=5,filesize=20M \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=logs \
-jar app.jar
Java 8 uses legacy GC logging flags
java \
-Xms2g \
-Xmx2g \
-Xloggc:logs/gc.log \
-XX:+PrintGCDetails \
-XX:+PrintGCDateStamps \
-XX:+UseGCLogFileRotation \
-XX:NumberOfGCLogFiles=5 \
-XX:GCLogFileSize=20M \
-jar app.jar
Useful jcmd commands
jcmd <pid> VM.version
jcmd <pid> VM.flags
jcmd <pid> GC.heap_info
jcmd <pid> GC.class_histogram
jcmd <pid> Thread.print
jcmd <pid> JFR.start name=gc-investigation settings=profile duration=5m filename=gc-investigation.jfr
jcmd <pid> GC.heap_dump heapdump.hprof
jcmd <pid> GC.finalizer_info
jcmd <pid> VM.native_memory summary
- Collection cause and phase.
- Pause and concurrent duration.
- Heap occupancy before and after GC.
- Frequency, promotion and collector fallback events.
- G1 regions, humongous objects or ZGC stalls.
- Allocation hot spots and object samples.
- CPU use near collection events.
- Safepoints, locks and thread scheduling.
- Class loading and code compilation.
- Application events around a latency incident.
Start with -XX:NativeMemoryTracking=summary or detail before using VM.native_memory. NMT tracks JVM-internal native allocations, not every allocation made by arbitrary third-party native code.
Java GC Troubleshooting: Symptom → Evidence → Next Action
-Xmx, stacks, direct buffers, Metaspace, code cache and native libraries.Retain GC logs, JFR, memory metrics, thread dumps and—when operationally safe—a heap dump. A restart can erase the object graph and growth pattern needed to identify the cause.
Evidence-First Java Garbage Collection Tuning Workflow
Define the objective
Specify measurable targets such as p99 pause time, request latency, batch duration, CPU budget or maximum container memory.
Record the complete baseline
Capture JDK vendor and version, collector, flags, heap, live set, allocation rate, pause percentiles, throughput and process RSS.
Reproduce the actual workload
Include cache warm-up, real payload sizes, traffic bursts, CPU limits, world or data size and steady-state duration.
Classify the failure
Separate high allocation, retained live data, inadequate heap, native memory, CPU starvation and collector-specific behaviour.
Change one important variable
Test one heap, collector or application adjustment. Changing a wall of flags makes the result difficult to explain or reverse.
Canary and compare
Compare pause percentiles, throughput, CPU, after-GC occupancy, process memory and error rate before wider rollout.
- Keep rotating GC logs enabled.
- Use bounded caches and queues.
- Reduce unnecessary allocation where profiling supports it.
- Test JDK upgrades as performance changes.
- Leave CPU and memory capacity for concurrent collectors.
- Calling
System.gc()on a timer. - Selecting a collector from one benchmark headline.
- Setting
-Xmxequal to a container limit. - Hiding a leak through scheduled restarts.
- Copying flags written for another JDK or workload.
Strong, Soft, Weak and Phantom References
SoftReferenceMemory-sensitive reachabilityWeakReferenceWeak reachabilityPhantomReferencePost-mortem notificationget()ReferenceQueue-based cleanup coordination and advanced resource bookkeeping.Finalization and external resources
- Use try-with-resources for
AutoCloseableobjects. - Define explicit resource ownership.
- Use Cleaner only as a defensive safety net.
- Monitor pending finalizers while removing legacy finalization.
- Relying on
finalize()to close files or sockets. - Assuming GC will run before an external resource limit is reached.
- Using finalization timing as application logic.
- Ignoring a growing pending-finalization queue.
It can create security, performance and reliability problems. Use jcmd <pid> GC.finalizer_info to inspect objects waiting for finalization while modernizing legacy code.
Java Garbage Collection in Docker and Kubernetes
A container memory limit covers the complete process, not only the Java heap. The process can be killed while heap usage remains below -Xmx.
Reserve space outside -Xmx
Account for stacks, direct buffers, Metaspace, code cache, GC structures and native libraries.
Concurrent GC must be scheduled
Severe CPU throttling can prevent a concurrent collector from completing work before allocation pressure catches up.
Track allocation and latency
Heap occupancy alone can hide fast allocation. Include request rate, allocation rate, CPU and pause metrics in scaling decisions.
java \
-XX:MaxRAMPercentage=70 \
-XX:NativeMemoryTracking=summary \
-Xlog:gc*,safepoint:file=/logs/gc.log:time,uptime,level,tags:filecount=5,filesize=20M \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=/dumps \
-jar app.jar
The correct heap percentage depends on thread count, direct buffers, frameworks, native libraries, class count, collector and the actual container limit.
Java Garbage Collection for Minecraft
Minecraft Java Edition uses the JVM, but a desktop client, vanilla server, Paper server and heavily modded server have different allocation and latency patterns.
Start with launcher defaults
Use the Java version required by the installed Minecraft release. Change memory or collector arguments only for a reproducible problem.
Separate GC lag from tick lag
Plugins, mods, entities, chunk generation, view distance, storage and CPU saturation can cause lag without a long GC pause.
Use Paper-specific documentation
Paper provides a G1-oriented Aikar flag guide. Those settings are server-specific and should not be treated as universal JVM or client flags.
Safe Minecraft GC workflow
Back up the original JVM arguments
Keep a copy of launcher or server arguments so an unsuccessful change can be reversed.
Leave memory outside the heap
Do not give Java all physical or hosting-plan RAM. The operating system, JVM-native memory and server panel need capacity.
Measure the correct symptom
Compare tick time, GC pauses, CPU use, disk latency, chunk generation and plugin or mod activity.
Change one setting at a time
Use the same world, players, view distance and workload for before-and-after testing.
- Use a supported Java runtime for the Minecraft version.
- Start with default G1 behaviour.
- Allocate enough heap without exhausting host memory.
- Use current Paper guidance for a Paper server.
- Capture GC logs before testing a different collector.
- Pasting Paper server flags into the desktop client.
- Allocating all available memory to
-Xmx. - Assuming additional heap improves tick performance.
- Using flags written for another Java release.
- Blaming GC without profiling plugins or mods.
Paper’s guide disables explicit collection to protect servers from plugins that request expensive collections. Validate any equivalent flag for your own non-Minecraft application rather than copying it automatically.
Java Garbage Collection Interview Questions
Strong interview answers describe reachability, collector trade-offs and the evidence required during a real production incident.
Core questions
1. When does an object become eligible for garbage collection?
When no live path from any GC root can reach it. Going out of scope or assigning null matters only when it removes the final reachable path.
2. What are common GC roots?
References from active thread stacks, static fields, JNI handles and internal JVM runtime structures.
3. What is the difference between heap and stack memory?
The shared heap contains objects and arrays managed by GC. Each platform thread has stack frames containing local values and references; frames disappear as methods return.
4. Why are Java collectors generational?
Many workloads create numerous short-lived objects. Frequent young-memory collection can therefore recover substantial space without processing the complete old live set each time.
5. What does stop-the-world mean?
Application threads are paused so the JVM can perform work requiring a coordinated global state. Concurrent collectors reduce the work inside these pauses but do not eliminate all pauses.
6. Is System.gc() guaranteed to run GC immediately?
No. It requests collection. JVM flags and the selected collector determine whether the request causes an expensive collection, a concurrent action or no collection.
7. How can Java have a memory leak when GC is automatic?
A leak occurs when the application unintentionally keeps objects reachable through caches, static collections, queues, listeners, thread locals or class loaders.
8. What is the difference between G1 and ZGC?
G1 aims for a practical balance of throughput and pause goals through region-based incremental collection. ZGC moves substantially more work into concurrent phases to target extremely short pauses, with different CPU and memory-headroom costs.
Java garbage collection interview questions for experienced developers
9. Old-generation usage rises after every comparable GC. What do you investigate?
Confirm that comparable old or whole-heap cycles occurred, correlate growth with load and deployments, capture a heap dump or JFR heap statistics, then inspect dominators, caches, queues, class loaders, listeners and thread locals.
10. Latency is high but reported GC pauses are short. What comes next?
Check non-GC safepoints, CPU throttling, lock contention, thread pools, JIT compilation, page faults, storage, network calls and downstream services through JFR and system telemetry.
11. A Kubernetes pod was OOMKilled without a Java heap exception. Why?
Total process memory likely crossed the cgroup limit. Investigate direct buffers, thread stacks, Metaspace, code cache, GC structures, JNI allocations and the relationship between -Xmx and the pod limit.
12. How would you choose between G1, ZGC and Parallel GC?
Define latency and throughput goals, establish a baseline, test realistic allocation and live-set behaviour, account for CPU and memory headroom, then compare pause percentiles, total throughput and footprint.
13. What are G1 humongous objects?
Objects at least half of a G1 region receive special old-generation allocation. They can span multiple contiguous regions and may create unusual space or fragmentation pressure.
14. What evidence should be collected before changing JVM flags?
JDK vendor and version, complete JVM command line, GC logs, JFR, heap and native-memory metrics, CPU limits, allocation rate, live set, pause percentiles, traffic pattern and the business symptom.
Explain the mechanism, describe the trade-off, name the evidence you would collect and state how you would validate the proposed change.
Official Java Garbage Collection Sources
The practical explanation is provided above. Use these primary sources when confirming release-specific behaviour or planning a production change.
HotSpot GC Tuning Guide
Collector selection, ergonomics, generational concepts, G1, ZGC and general tuning guidance.
Open Oracle’s Java 26 GC guide59-Page Oracle GC Guide
Complete diagrams, option tables, collector internals, explicit GC, finalization and reference processing.
Open the official Java 26 PDFJFR, Heap Dumps and NMT
Official commands and investigation guidance for running JVMs and memory incidents.
Open Oracle diagnostic toolsRuntime Data Areas
Specification-level definitions of heap, JVM stacks, frames, method area and runtime constant pools.
Open JVM runtime data areasjava.lang.ref
Exact API semantics for soft, weak, phantom and cleaner-related reference processing.
Open the Java reference APIG1 Synchronization Improvements
Primary OpenJDK description of the G1 throughput work delivered in Java 26.
Open JEP 522Java Garbage Collection FAQ
What is garbage collection in Java?
Garbage collection is the JVM process that identifies heap objects no longer reachable from live roots and reclaims or reorganizes their memory.
How does the Java garbage collection mechanism work?
The collector starts from GC roots, traces reachable objects, processes reference objects and reclaims unreachable space through sweeping, evacuation, compaction or collector-specific combinations.
What are the main Java garbage collection types?
Current HotSpot choices include Serial, Parallel, G1 and ZGC. Shenandoah is available in supported OpenJDK distributions and platforms. CMS is historical and was removed in Java 14.
Which collector is the Java 26 default?
Java 26 HotSpot normally selects G1 on server-class machines and Serial in smaller constrained environments. Explicit collector flags override the ergonomic choice.
Is G1 better than ZGC?
Neither is universally better. G1 balances throughput and pause goals, while ZGC prioritizes extremely short pauses and performs more work concurrently. Compare them under the same workload and capacity limits.
What triggers Java garbage collection?
Common triggers include young-space exhaustion, heap occupancy thresholds, failed allocations, metadata pressure, collector policy and explicit collection requests.
Can Java garbage collection be forced?
System.gc() requests collection but does not guarantee an immediate or specific event. JVM flags and collector behaviour determine how the request is handled.
What does Full GC mean?
Full GC generally describes a broad or whole-heap collection. Exact causes differ by collector. Repeated Full GC with little reclaimed memory requires investigation.
How can Java have a memory leak when it uses GC?
GC cannot reclaim objects that remain reachable. Caches, static collections, listeners, queues, thread locals and class loaders can retain objects the application no longer needs.
Does Java GC manage stack and direct memory?
GC manages heap objects. Stack frames have thread and method lifecycles, while direct buffers and many native allocations live outside the heap. Stack and native references can still influence reachability and total process memory.
How do I enable Java GC logging?
On Java 9 and newer, use unified logging such as -Xlog:gc*,safepoint:file=gc.log:time,uptime,level,tags. Add file rotation for long-running production services.
What causes GC overhead limit exceeded?
It commonly occurs when the JVM spends excessive time collecting while reclaiming very little memory. Investigate a near-full live heap, object retention, insufficient sizing and extreme allocation.
What is the best Java garbage collector for Minecraft?
There is no universal winner. Start with the supported Java runtime and default G1 behaviour. Paper server operators should use current Paper guidance and measure tick, allocation, CPU and GC data before testing another collector.
Does increasing heap size always reduce GC pauses?
No. Additional heap can reduce collection frequency and provide headroom, but it can also delay leak detection or change collection costs. Test heap size with the real live set, allocation rate and collector.
Production Next Steps
1. Record the JDK vendor, version, collector and complete JVM command line.
2. Enable rotating GC and safepoint logs.
3. Capture JFR, memory metrics and heap evidence while the problem occurs.
4. Classify heap, native-memory, CPU or application-retention problems.
5. Change one variable and validate it with realistic load.
Independent technical guide. Collector availability, defaults, flags and behaviour depend on the exact JDK version, vendor, operating system, architecture and deployment environment. Verify production changes against the documentation for the runtime actually in use. Last factual review: July 24, 2026.