Java Garbage Collection: JVM Memory, Types & Tuning

☕ Java 26 HotSpot guide • beginner to production troubleshooting

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.

🧠 JVM memory map 🔗 Roots and reachability 🧹 Mark, sweep and evacuation ⚙️ Serial, Parallel, G1 and ZGC 📈 GC logs, JFR and heap dumps 🎤 Experienced interview scenarios ⛏️ Minecraft client and server ✅ Reviewed July 24, 2026

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.

Eligibility

Unreachable means collectible

An object becomes eligible when no live reference path from a GC root reaches it.

Trigger

GC is demand-driven

Allocation pressure, generation occupancy, collector policy and failed allocations influence when work begins.

Pauses

Some coordination still pauses threads

Concurrent collectors reduce pause work, but current general-purpose collectors still require brief stop-the-world phases.

Limit

GC cannot remove reachable leaks

An unbounded cache, static map, queue or listener can keep unwanted objects alive indefinitely.

Best practical starting point

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

Loading...
Select province to begin
City list loads after province
Which day of the week is your pickup?
Select city — date auto-fills for known cities

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.

Grey Bin
Blue Box
Green Bin
What goes to the curb tonight

Next pickup date

Based on your collection day

days
Collection calendar

Garbage Recycling Green Bin

🔑 Bookmark this page to check your schedule every 2 weeks

Calculator based on biweekly alternating schedule. Always verify with your municipality or call 311 for holiday changes. garbage-collection.org
Java Memory Model and JVM memory areas are different topics

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.

Current Oracle guideJava 26 HotSpot
Default selectionG1 on server-class machines; Serial otherwise
Server-class heuristicAt least two processors and at least 1792 MB of physical memory.
JEP 523Universal G1 proposal
MeaningProposes choosing G1 in every environment when no collector is specified
Do not assumeThis proposal does not replace the documented Java 26 server-class selection rule.
G1 in Java 26JEP 522 delivered
ChangeReduced synchronization between application and GC threads
Resident meaningRe-test old performance assumptions after upgrading; do not automatically carry forward older tuning.
ZGCCurrent mode
Java 24 onwardZGC is generational; the old non-generational option was removed
Migration checkRemove obsolete instructions that tell current runtimes to enable a separate generational mode.
ShenandoahDistribution-dependent
Current stateGenerational mode is a product feature, but collector availability varies
ActionCheck the actual vendor build, operating system and supported flags before selecting it.
CMSHistorical collector
StatusRemoved from the JDK in Java 14
Interview answerExplain its history and limitations, but do not list it as a current Java 26 collector.
Compact Object Headers are a footprint feature—not a collector

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.

Java heapObjects and arrays
Managed byThe selected garbage collector
Common symptomOutOfMemoryError: Java heap space, rising live set or long collection cycles.
Thread stacksFrames, primitive locals and references
Managed byThread and method lifecycles
Common symptomStackOverflowError or failure to create additional native threads.
MetaspaceClass metadata
LocationNative memory outside the Java heap
Common symptomClass-loader retention, generated-class growth or OutOfMemoryError: Metaspace.
Code cacheJIT-compiled machine code
Managed byThe JVM compiler and code-cache subsystem
Common symptomReduced compilation activity or performance degradation when space becomes constrained.
Direct/native memoryNIO buffers, JNI and libraries
LocationOutside -Xmx
Common symptomDirect-buffer errors, process RSS growth or container OOMKill without a Java heap exception.
Collector structuresRemembered sets, mark maps and metadata
LocationMostly native process memory
Operational effectTotal process memory is normally larger than the configured Java heap.
GC can reclaim
  • 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.
GC does not automatically solve
  • 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.

Thread stacks
active local references
Static fields
loaded classes
JNI handles
native references
JVM internals
runtime roots
Eden / young regions Most ordinary objects begin here. A large proportion becomes unreachable quickly.
Survivor Objects retained across young collections.
Old regions Promoted or longer-lived data and collector-specific large-object handling.
Conceptual generational diagram based on the weak-generational hypothesis: many objects die soon after allocation, while a smaller set remains live much longer.

Conceptual G1 heap layout

E

Eden region for newer allocations.

S

Survivor region for young objects that remain reachable.

O

Old region containing longer-lived objects.

H

Humongous object spanning one or more old-generation regions.

G1 uses equally sized, non-contiguous regions. It can assign regions to eden, survivor, old, free or humongous roles as the heap changes.

Java Garbage Collection Mechanism in Depth

1

The application allocates objects

Most normal objects use a fast young-generation allocation path. Collector-specific large objects can bypass the ordinary young path.

2

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.

3

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.

4

GC roots are scanned

The collector starts from thread stacks, static fields, JNI handles and JVM structures, then traces the reachable object graph.

5

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.

6

Reference objects are processed

Soft, weak and phantom references follow weaker reachability rules than normal strong references and can interact with reference queues.

7

Memory is reclaimed or evacuated

The collector may sweep dead blocks, copy live objects, compact memory or reclaim entire source regions after evacuation.

8

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.

Tracing / markingFind the live graph
MethodStart at roots and follow references
OutcomeObjects not reached by the tracing process can become reclaimable.
SweepReuse dead blocks
MethodReturn memory occupied by unmarked objects to free-space structures
Trade-offCan leave fragmented free areas when compaction is not performed.
Copy / evacuateMove surviving objects
MethodCopy live objects out of selected memory and reclaim the complete source area
Trade-offCreates compact free space but needs destination capacity and reference updates.
CompactionReduce fragmentation
MethodMove live objects together
Trade-offMovement can be costly when large volumes of live data are processed during a pause.
Generational collectionGroup by object age
MethodCollect young memory frequently and older memory less often
BenefitTakes advantage of the common pattern that many objects die shortly after allocation.
Concurrent workRun beside the application
MethodPerform marking or relocation while application threads continue
Trade-offReduces pauses but consumes CPU and requires barriers to preserve correctness.
Minor, major and Full GC are not perfectly universal labels

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

Serial GC-XX:+UseSerialGC
Useful starting fitSmall applications, small heaps and constrained environments
Trade-offLow complexity and footprint, but collection work uses a single GC thread and application pauses.
Parallel GC-XX:+UseParallelGC
Useful starting fitBatch, ETL and throughput-first jobs
Trade-offMultiple collection threads improve completed work, but pause latency can be longer.
G1 GC-XX:+UseG1GC
Useful starting fitGeneral server applications balancing latency and throughput
Trade-offRegion-based and mostly concurrent, with pause goals rather than real-time guarantees.
ZGC-XX:+UseZGC
Useful starting fitStrict-latency services and large heaps
Trade-offVery short pauses with additional concurrent CPU and memory-headroom requirements.
Shenandoah-XX:+UseShenandoahGC
Useful starting fitLow-pause workloads on JDK builds that provide it
Trade-offAvailability, modes and support depend on the distribution and platform.
Selection rule

Start 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.

Choose both fields to see an evidence-based test path.

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.

Young-only phase

Frequent young collections

Eden and survivor regions are processed while old occupancy gradually approaches the concurrent-marking threshold.

Concurrent mark

Estimate old-region liveness

G1 discovers how much live data remains in old regions while performing much of the work beside the application.

Mixed collections

Young plus selected old regions

G1 adds efficient old regions to later collection sets and evacuates live objects out of them.

Humongous objects

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

Frequent young GCYoung space fills quickly
Possible causeHigh allocation rate or small adaptive young generation
Next evidenceAllocation profile, request payloads, TLAB statistics and pause percentiles.
Humongous allocationsLarge objects consume special regions
Possible causeLarge arrays, buffers, serialized payloads or region-size interaction
Next evidenceDetailed G1 logs, JFR allocation events and object-size distribution.
Evacuation failureDestination capacity became insufficient
Possible causeLow free-region headroom or sudden promotion pressure
Next evidenceLive set, heap sizing, promotion rate, concurrent-cycle timing and Full GC follow-up.
Repeated Full GCNormal incremental recovery failed
Possible causeLeak, insufficient heap, fragmentation or marking starting too late
Next evidenceAfter-GC occupancy, heap dump, collection cause and region statistics.
-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.

Avoid manually fixing G1’s young generation without evidence

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.

Pause objective

Sub-millisecond maximum target

ZGC minimizes stop-the-world work so pause duration is not proportional to the live heap size.

Main tuning lever

Provide enough maximum heap

ZGC needs space for the application’s live set and allocations that continue while concurrent collection is running.

Trade-off

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.

ZGC capacity test—not a universal production prescription
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
Allocation stall means the collector could not keep up

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

Rotating GC, safepoint and OOM evidence
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 8 HotSpot example
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

Running-JVM investigation
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
Use GC logs for
  • 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.
Use JFR for
  • 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.
Native Memory Tracking must be enabled at JVM startup

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

Old usage rises after GCPossible retained-object growth
CollectHeap dump, JFR heap statistics and class histogram
Check nextDominator tree, cache bounds, queues, listeners, thread locals and class loaders.
Frequent Full GCBroad emergency cleanup
CollectGC cause, before/after heap and promotion data
Check nextLeak, insufficient headroom, allocation burst, fragmentation or explicit-GC caller.
Long latency but short GC pausesGC may not be the cause
CollectJFR, safepoint logs, CPU and thread dumps
Check nextCPU throttling, locks, I/O, JIT compilation, page faults and downstream services.
G1 evacuation failureInsufficient destination space
CollectRegion statistics, live set and promotion rate
Check nextHeap headroom, concurrent-cycle timing, humongous pressure and allocation spikes.
ZGC allocation stallConcurrent recovery fell behind
CollectAllocation rate, CPU throttling and heap occupancy
Check nextIncrease tested headroom, reduce allocation or provide sufficient CPU capacity.
Metaspace OOMClass metadata growth
CollectClass-loader statistics, histogram and JFR class events
Check nextDynamic class generation, redeploy leaks and retained application class loaders.
Direct-buffer OOMOff-heap buffer pressure
CollectBuffer-pool metrics, NMT and framework telemetry
Check nextPooling, buffer lifetime, configured direct-memory limit and native headroom.
Container OOMKilledNo Java heap exception required
CollectPod status, cgroup metrics, process RSS and NMT
Check next-Xmx, stacks, direct buffers, Metaspace, code cache and native libraries.
Preserve evidence before restarting

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

1

Define the objective

Specify measurable targets such as p99 pause time, request latency, batch duration, CPU budget or maximum container memory.

2

Record the complete baseline

Capture JDK vendor and version, collector, flags, heap, live set, allocation rate, pause percentiles, throughput and process RSS.

3

Reproduce the actual workload

Include cache warm-up, real payload sizes, traffic bursts, CPU limits, world or data size and steady-state duration.

4

Classify the failure

Separate high allocation, retained live data, inadequate heap, native memory, CPU starvation and collector-specific behaviour.

5

Change one important variable

Test one heap, collector or application adjustment. Changing a wall of flags makes the result difficult to explain or reverse.

6

Canary and compare

Compare pause percentiles, throughput, CPU, after-GC occupancy, process memory and error rate before wider rollout.

Good practice
  • 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.
Anti-patterns
  • Calling System.gc() on a timer.
  • Selecting a collector from one benchmark headline.
  • Setting -Xmx equal to a container limit.
  • Hiding a leak through scheduled restarts.
  • Copying flags written for another JDK or workload.

Strong, Soft, Weak and Phantom References

Strong referenceNormal Java reference
GC effectKeeps an object strongly reachable
Typical useNormal application ownership and object graphs.
SoftReferenceMemory-sensitive reachability
GC effectMay be cleared in response to memory demand
CautionNot a predictable substitute for an explicitly bounded cache.
WeakReferenceWeak reachability
GC effectCan be cleared when no strong or soft path remains
Typical useMetadata associations, canonical mappings and weak-key structures.
PhantomReferencePost-mortem notification
GC effectThe referent cannot be retrieved through get()
Typical useReferenceQueue-based cleanup coordination and advanced resource bookkeeping.

Finalization and external resources

Preferred
  • Use try-with-resources for AutoCloseable objects.
  • Define explicit resource ownership.
  • Use Cleaner only as a defensive safety net.
  • Monitor pending finalizers while removing legacy finalization.
Avoid
  • 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.
Finalization is deprecated and discouraged

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.

Heap headroom

Reserve space outside -Xmx

Account for stacks, direct buffers, Metaspace, code cache, GC structures and native libraries.

CPU capacity

Concurrent GC must be scheduled

Severe CPU throttling can prevent a concurrent collector from completing work before allocation pressure catches up.

Autoscaling

Track allocation and latency

Heap occupancy alone can hide fast allocation. Include request rate, allocation rate, CPU and pause metrics in scaling decisions.

Container-oriented starting example
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
Seventy per cent is an example—not a universal safe ratio

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.

🎮 Client

Start with launcher defaults

Use the Java version required by the installed Minecraft release. Change memory or collector arguments only for a reproducible problem.

🖥️ Server

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.

📄 Paper

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

1

Back up the original JVM arguments

Keep a copy of launcher or server arguments so an unsuccessful change can be reversed.

2

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.

3

Measure the correct symptom

Compare tick time, GC pauses, CPU use, disk latency, chunk generation and plugin or mod activity.

4

Change one setting at a time

Use the same world, players, view distance and workload for before-and-after testing.

Sensible baseline
  • 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.
Common mistakes
  • 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 explicit-GC advice is workload-specific

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.

Experienced-answer structure

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.

Full PDF

59-Page Oracle GC Guide

Complete diagrams, option tables, collector internals, explicit GC, finalization and reference processing.

Open the official Java 26 PDF
Diagnostics

JFR, Heap Dumps and NMT

Official commands and investigation guidance for running JVMs and memory incidents.

Open Oracle diagnostic tools
JVM specification

Runtime Data Areas

Specification-level definitions of heap, JVM stacks, frames, method area and runtime constant pools.

Open JVM runtime data areas
Reference API

java.lang.ref

Exact API semantics for soft, weak, phantom and cleaner-related reference processing.

Open the Java reference API
JEP 522

G1 Synchronization Improvements

Primary OpenJDK description of the G1 throughput work delivered in Java 26.

Open JEP 522

Java 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.