JVM Flags: Standard, -X, and -XX Options Explained

Learn how standard, -X, and -XX JVM flags differ, which options apply to HotSpot JDK 26, and how to measure and roll back tuning changes safely.

published: reading time: 20 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn how standard, -X, and -XX JVM flags differ, which options apply to HotSpot JDK 26, and how to measure and roll back tuning changes safely.

Introduction

JVM flags can change heap sizing, garbage collection, JIT behavior, and diagnostic output. Their names and defaults are easy to copy; their effects depend on the runtime and workload. This guide explains the flag categories and shows how to evaluate a change with measurements and a rollback path.

Unless a section says otherwise, non-standard options below refer to Oracle HotSpot JDK 26. Other JDK vendors, HotSpot builds, releases, and collectors can support different options or defaults. Check the documentation for the exact runtime you deploy, then inspect the process with java -version and jcmd <pid> VM.flags -all. Examples describe option syntax; they are not a recommended production configuration.

When to Use This / When Not to Use This

Use JVM flags when:

  • You need to tune heap size based on actual memory pressure observations
  • GC pause times are causing SLA violations and you need to select or configure a specific collector
  • You are diagnosing a specific issue (e.g., class metadata space exhaustion, stack overflow)
  • You want to enable diagnostic output for post-incident analysis

Do not use JVM flags when:

  • You have not measured the problem first. Tuning without data is guesswork.
  • Your application is undersized at the architecture level. More heap does not fix a flawed design.
  • You are applying “magic numbers” copied from blog posts without understanding the tradeoffs.

JVM Flag Categories

The Java launcher groups options by how broadly they are supported:

Category Prefix What it means
Standard None Guaranteed by the Java launcher specification across JVM implementations
Extra -X HotSpot-specific options that may change between releases
Advanced -XX HotSpot implementation options; some are experimental or diagnostic

Standard options cover common tasks such as choosing a class path or printing the runtime version. The -X and -XX names are not portability promises. For a deployed runtime, use that release’s option reference and inspect the values that process actually received.

Standard Options

Examples of standard launcher options include:

java -cp app.jar com.example.Main
java -version
java -help

Options such as the old -client selector are not part of a current tuning recipe. Check the launcher reference for the Java release you support before relying on a historical option.

Non-Standard Options (-X)

The following syntax examples are HotSpot-specific. The names are supported by Oracle HotSpot JDK 26; exact defaults and behavior can vary by release and platform:

  • -Xms<size> — initial Java heap size
  • -Xmx<size> — maximum Java heap size
  • -Xss<size> — Java thread stack size
  • -Xmn<size> — young-generation size; avoid fixing it when using G1 unless measurements justify it
  • -Xlog:gc* — unified GC logging
  • -Xshare:<mode> — class-data sharing mode

Older options such as -Xprof and -Xrunhprof are omitted because they are not part of the JDK 26 option set.

Advanced Options (-XX)

The examples below use Oracle HotSpot JDK 26. A flag may be collector-specific, diagnostic, experimental, or unavailable in another build. Confirm support with the release’s java command reference and java -XX:+PrintFlagsFinal -version before using it.

Heap and Memory Flags

-XX:InitialHeapSize=<size>      # Equivalent to -Xms
-XX:MaxHeapSize=<size>          # Equivalent to -Xmx
-XX:NewSize=<size>              # Young-generation sizing; collector-dependent
-XX:MaxNewSize=<size>           # Young-generation sizing; collector-dependent
-XX:SurvivorRatio=<ratio>       # Eden-to-survivor sizing; collector-dependent
-XX:MetaspaceSize=<size>        # Threshold that can trigger metadata GC, not preallocated space
-XX:MaxMetaspaceSize=<size>     # Optional cap on native class-metadata memory
-XX:MinHeapFreeRatio=<percent>  # Minimum free-heap ratio after collection
-XX:MaxHeapFreeRatio=<percent>  # Maximum free-heap ratio after collection

MetaspaceSize is an adaptive garbage-collection threshold. MaxMetaspaceSize places a hard limit on class metadata and should be set only when measurements and a memory budget support it. G1 manages its young generation automatically; fixing generation sizes can interfere with its pause-time heuristics.

Garbage-Collection Flags

These collector selectors are available in Oracle HotSpot JDK 26. Select one collector at a time, and verify that the target JDK build includes it:

-XX:+UseSerialGC      # Small or simple workloads
-XX:+UseParallelGC    # Throughput-oriented workloads
-XX:+UseG1GC          # General-purpose, pause-time goals
-XX:+UseZGC           # Low-latency collector
-XX:+UseShenandoahGC  # Low-pause collector; availability depends on the build

CMS was removed in JDK 14, so -XX:+UseConcMarkSweepGC is a historical option, not a current choice. With G1, -XX:MaxGCPauseMillis=<time> is a soft target, not a guarantee. The JDK 26 launcher documents -XX:G1HeapRegionSize=<size> as a power of two from 1 MB to 32 MB; by default, G1 chooses a region size ergonomically. See the JDK 26 Java launcher reference for the documented option range.

In JDK 26, -XX:+UseZGC selects generational ZGC; do not add the obsolete -XX:+ZGenerational switch. Some collector options and defaults differ in earlier JDKs.

JIT Compiler Flags

These HotSpot JDK 26 examples cover tiered compilation and diagnostics:

-XX:+TieredCompilation  # Enables tiered compilation; enabled by default
-XX:TieredStopAtLevel=<n>
-XX:+PrintCompilation    # Prints a message when a method is compiled

Compilation thresholds and heuristics are implementation details that can change. Start with the defaults and profile before changing them.

Architecture: JVM Flag Processing Flow

Understanding how flags flow through the JVM helps diagnose configuration errors:

graph TD
    A[JVM Process Start] --> B[Argument Parsing]
    B --> C{Flag Type?}
    C -->|Standard| D[Apply Standard Options]
    C -->|Non-Standard -X| E[Apply -X Options]
    C -->|Advanced -XX| F[Apply -XX Options]
    D --> G[Initialize subsystems]
    E --> G
    F --> G
    G --> H[Verify constraints]
    H --> I{Valid?}
    I -->|No| J[Print error and exit]
    I -->|Yes| K[JVM Ready]
    J --> L[Show relevant diagnostic]

Measure First, Then Tune and Roll Back

Treat a flag change as an experiment. Keep the original launch arguments so the change can be reverted without reconstructing the old configuration.

  1. Record the baseline. Save the JDK vendor and full version, application build, launch arguments, container CPU and memory limits, and a representative workload. Measure latency percentiles, throughput, CPU, process/container memory, and GC activity.

  2. Inspect the running JVM. JDK 26 HotSpot supports these diagnostic commands:

    jcmd <pid> VM.flags -all
    jcmd <pid> GC.heap_info
    jcmd <pid> Compiler.codecache

    jcmd must run on the same host as the process, using the same effective user and group. Some commands can affect the target JVM; check the command’s documented impact before using it during a latency-sensitive window.

  3. Change one variable. Tie the change to a measured problem and record the expected result. Do not combine heap, collector, and JIT changes in the same experiment.

  4. Compare under the same load. Include warm-up and enough runtime to observe normal GC cycles. Use a canary or staging deployment, and compare the same latency, throughput, CPU, memory, and GC signals against the baseline.

  5. Roll back on regression. Restore the saved launch arguments if the change misses its target, increases resource use beyond budget, or causes errors. Keep the measurements and GC logs with the change record.

For a temporary GC log on HotSpot JDK 26, add this diagnostic option to the process being measured:

-Xlog:gc*:file=gc.log:time,uptime,level,tags

Logging is evidence for the experiment; it does not make a tuning value safe by itself. Check disk space and log retention for the target environment.

Observability Checklist

Before and after changing JVM flags, verify these signals:

  • Review GC logs for pause times, collection frequency, and heap trends
  • Check heap details with jcmd <pid> GC.heap_info
  • Check native-memory categories with jcmd <pid> VM.native_memory summary only when NMT was enabled at startup
  • Verify active HotSpot flags with jcmd <pid> VM.flags -all
  • Measure application throughput under realistic load
  • Confirm container memory limits align with JVM heap settings
  • Verify code cache is not becoming a bottleneck
  • Check metaspace usage for class metadata leaks

Production Failure Scenarios

Scenario 1: Heap Limit Exceeds the Container Budget

Problem: An explicit -Xmx larger than the container’s memory limit can let the total process footprint exceed that limit. The Java heap is only one part of process memory; metaspace, code cache, thread stacks, direct buffers, and native libraries also consume memory.

Response: On Linux, HotSpot JDK 26 detects container limits by default. Confirm what the JVM sees with java -Xlog:os+container=trace -version, then compare the process’s total memory use with its container limit under representative load. Set an explicit heap ceiling only after budgeting for non-heap memory and required headroom. There is no universal heap percentage that fits every application.

Scenario 2: G1 Region Size Is Outside the Supported Range

Problem: -XX:G1HeapRegionSize=64m is outside Oracle HotSpot JDK 26’s documented 1–32 MB range, so startup rejects the option. The value must also be a power of two.

# Invalid for Oracle HotSpot JDK 26
java -XX:G1HeapRegionSize=64m -version

Response: Leave region sizing to G1 unless GC logs point to a specific issue. If you have evidence for testing an override, use a value supported by the target runtime and compare it under the same workload; 16m is a documented valid value, not a default recommendation.

Scenario 3: A Removed CMS Flag Is Still in the Launch Script

Problem: -XX:+UseConcMarkSweepGC was removed in JDK 14. Passing it to a current JVM causes startup to fail rather than selecting a fallback collector.

Response: Remove the obsolete selector and compare supported collectors using the application’s latency, throughput, CPU, and memory targets. A migration from CMS does not imply that one collector is best for every workload. See JEP 363.

Scenario 4: A Metaspace Cap Causes Class-Loading Failures

Problem: A low -XX:MaxMetaspaceSize can cause OutOfMemoryError: Metaspace as an application or framework loads classes. A cap that worked in one environment may be too small after adding plugins, proxies, or class loaders.

Response: Measure process memory and class-loading behavior before setting a cap. If Native Memory Tracking was enabled at JVM startup, inspect it with jcmd <pid> VM.native_memory summary; otherwise use GC logs, class-loader statistics, and container-level memory measurements. Keep the previous launch configuration ready to restore during a staged rollout.

Trade-off Table

Option or choice Potential benefit Cost or limit How to decide
-Xms equal to -Xmx Avoids heap growth between different configured bounds Can commit more heap earlier and reduce room for other process memory Compare startup, RSS, and GC behavior under the expected load
G1 Balances throughput and pause-time goals with adaptive sizing A pause target is a soft goal; tuning can trade throughput for pauses Start with defaults and change a setting only to address a measured issue
Parallel GC Can favor throughput Stop-the-world pauses may be longer Test against a throughput target and latency limit
ZGC Targets low pauses even with large heaps Uses concurrent CPU work; memory and throughput depend on the workload Measure on the actual JDK, hardware, and allocation pattern
Shenandoah Concurrent collection with low-pause goals Availability and defaults vary by JDK build; concurrent work uses CPU Confirm build support and benchmark the service
Tiered compilation Supports quick profiling followed by optimized compilation Compilation consumes CPU and code-cache space Keep defaults unless a profile identifies a JIT-related issue

Operational Notes

JVM flags are configuration controls, not an isolation boundary. Restrict who can change launch arguments or attach diagnostic tools to a production process. In shared environments, use operating-system or container controls to isolate workloads, and enable diagnostic logging or Native Memory Tracking only when their operational cost is understood.

Common Pitfalls / Anti-Patterns

1. Treating heap size as the only memory setting.

Heap is only part of the process footprint. Account for metaspace, code cache, thread stacks, direct buffers, native libraries, and any sidecars sharing the same container limit.

2. Selecting a collector by reputation.

Serial, Parallel, G1, ZGC, and Shenandoah have different goals and trade-offs. Choose from workload measurements and service objectives, not a universal ranking.

3. Treating -XX:MaxGCPauseMillis as a deadline.

For G1 and Parallel GC, this is a soft target. The JVM makes a best effort and may miss it when the workload or available heap prevents the target from being met.

4. Setting -Xms equal to -Xmx automatically.

Equal bounds can make behavior more predictable, but may commit memory earlier. Compare the process footprint and startup behavior before choosing that configuration.

5. Capping metaspace without measuring class metadata.

-XX:MaxMetaspaceSize can turn a metadata growth pattern into an application failure. Confirm the runtime’s metadata usage and leave capacity for expected class loading.

6. Copying flags from another JDK or workload.

Non-standard flags and defaults can change by release, vendor, platform, and collector. Record the target runtime and validate a single change against a reproducible baseline.

Quick Recap Checklist

  • Standard launcher options are portable; -X and -XX options are implementation-specific.
  • The flag examples in this article target Oracle HotSpot JDK 26 unless a version is named explicitly.
  • Confirm the actual runtime and active options before editing a launch configuration.
  • Account for non-heap memory when sizing a containerized JVM.
  • G1 selects its region size ergonomically; a manual override must be valid for the target release and justified by measurements.
  • CMS was removed in JDK 14; remove its selector when migrating to a current JDK.
  • Measure a baseline, change one variable, compare under the same load, and keep a rollback path.
  • Use GC logs and diagnostic commands to investigate a specific symptom; do not treat a flag list as a production recipe.

Interview Questions

1. What is the difference between -X and -XX JVM flags?

Both are HotSpot-specific option families. The launcher reference groups -X options as extra options and -XX options as advanced options. Their availability and behavior can change between releases, so check the documentation for the JDK you deploy rather than treating either prefix as portable.

2. How do you correctly size heap for a JVM running inside a container?

Start with the container memory limit and measure total process memory under representative load. The heap shares that limit with metaspace, code cache, thread stacks, direct buffers, native libraries, and other processes. HotSpot JDK 26 enables Linux container support by default, but an explicit heap ceiling still needs to leave room for non-heap memory. Do not assume one percentage fits every service.

3. What happens if you set -Xms differently from -Xmx?

-Xms sets the initial heap size and -Xmx sets the maximum. When the values differ, the heap can grow within those bounds. Equal values remove that range, but may commit memory earlier; compare startup, process memory, and GC behavior before choosing equal bounds.

4. Why is CMS collector deprecated and what should you use instead?

CMS was deprecated in JDK 9 and removed in JDK 14. There is no single replacement that is best for every workload. Compare supported collectors on the target JDK using the service’s pause, throughput, CPU, and memory requirements.

5. What is native memory tracking and when should you enable it?

HotSpot Native Memory Tracking (NMT) reports JVM native-memory categories, including class metadata, code cache, thread stacks, and internal allocations. Enable it at JVM startup with -XX:NativeMemoryTracking=summary or detail, then inspect it with jcmd <pid> VM.native_memory summary. Its overhead depends on the workload and tracking level, so measure that cost before enabling it continuously.

6. How does tiered compilation work and when should you disable it?

HotSpot tiered compilation uses quick compilation for early execution and more optimizing compilation for methods that stay hot. It is enabled by default in the JDK 26 HotSpot configuration described here. Disabling it changes warm-up and peak-performance behavior; do so only to test a specific, measured problem and retain a rollback path.

7. What is the difference between G1GC and ZGC from a tuning perspective?

G1 adaptively sizes work to pursue a soft pause-time target, while ZGC is designed for low pauses and performs more concurrent work. In Oracle HotSpot JDK 26, -XX:+UseZGC enables generational ZGC; the separate -XX:+ZGenerational switch is not part of this release’s option set. Compare CPU, throughput, memory, and pauses on the target workload instead of assuming a fixed overhead or pause duration.

8. What does -XX:+UseContainerSupport actually do?

On Linux, HotSpot uses container CPU and memory limits to inform resource ergonomics. In Oracle HotSpot JDK 26, container support is enabled by default; -XX:-UseContainerSupport disables it. It does not guarantee that a manually configured heap leaves enough room for non-heap process memory.

9. How do you diagnose which JVM flags are actually applied?

For a running HotSpot JDK 26 process, use jcmd <pid> VM.flags -all to print supported flags and current values. To inspect defaults for a separate JVM launch, run java -XX:+PrintFlagsFinal -version. Check the vendor and version as well, since the set of flags differs between runtimes.

10. What is the HeapDumpOnOutOfMemoryError flag and why is it critical for production?

-XX:+HeapDumpOnOutOfMemoryError asks HotSpot to write a heap dump for an OutOfMemoryError caused by Java heap exhaustion. It does not cover every native-memory or other resource failure. Pair it with a writable, capacity-checked dump location and an incident process that protects the dump because it can contain sensitive application data.

11. What is the relationship between MetaspaceSize and MaxMetaspaceSize?

-XX:MetaspaceSize is the initial threshold that can trigger a metadata garbage collection; it is not a preallocated metaspace size. -XX:MaxMetaspaceSize is an optional hard cap on native class-metadata memory. The cap is unlimited by default in Oracle HotSpot JDK 26, so set one only after measuring expected class loading and container memory use.

12. What JVM flags would affect JIT compilation behavior?

For Oracle HotSpot JDK 26, -XX:+TieredCompilation controls tiered compilation and is enabled by default. -XX:TieredStopAtLevel changes the highest compilation tier, while -XX:+PrintCompilation prints compilation events for diagnostics. Avoid tuning compiler heuristics without a profile that shows a JIT-related bottleneck.

13. What is the code cache and how do you tune its size?

The code cache stores compiled native code. Its size is selected ergonomically and can vary by runtime configuration; there is no universal default size to copy. Inspect it with jcmd <pid> Compiler.codecache and consult the target JDK’s -XX:ReservedCodeCacheSize documentation before changing a limit.

14. When would you use -XX:+UseSerialGC in production?

Oracle’s JDK 26 launcher documentation describes Serial GC as a fit for small and simple applications that do not need special GC functionality. Decide from the workload’s memory, CPU, and pause requirements; a heap-size cutoff such as 100 MB is not a general rule.

15. How do thread stack sizing flags affect application resources?

-Xss controls the Java thread stack size in HotSpot. A smaller stack can reduce native memory per thread but may cause StackOverflowError; a larger one consumes more address space and memory as threads grow. Defaults vary by platform and runtime, so measure thread count and stack needs before changing it.

16. What is the difference between -XX:+PrintFlagsFinal and -XX:+PrintFlagsInitial?

-XX:+PrintFlagsFinal outputs the complete list of all JVM flags with their final values after JVM initialization, including those set explicitly, those computed from other flags, and default values. -XX:+PrintFlagsInitial shows only the initial values before any argument processing. Use -XX:+PrintFlagsFinal to verify exactly which flag values are in effect for a running JVM.

17. How does -XX:+AlwaysPreTouch affect memory initialization?

In HotSpot JDK 26, -XX:+AlwaysPreTouch asks the VM to touch every Java heap page after requesting it from the operating system and before handing memory to the application. This can increase startup work and move memory use earlier. Benchmark it under the target OS and container limits; it does not replace memory budgeting.

18. What does -XX:+UseLargePages enable and when should you use it?

-XX:+UseLargePages asks HotSpot to use large pages when the operating system and runtime environment support them. Page sizes, availability, and setup differ across platforms, so do not assume a fixed 2 MB page or a particular privilege requirement. Test with OS-level metrics and verify that the JVM actually obtained large pages.

19. What is the purpose of -XX:SoftRefLRUPolicyMSPerMB?

In HotSpot JDK 26, -XX:SoftRefLRUPolicyMSPerMB controls how long softly reachable objects are retained, measured in milliseconds per megabyte of free heap for the client VM or maximum heap for the server VM. The documented default is one second per megabyte, with different effects depending on VM mode and heap sizing. Treat this as an implementation detail and avoid using soft references as a predictable cache policy.

20. How do you use JVM flags to diagnose OutOfMemoryError causes?

First identify which resource failed from the error and process/container metrics. For Java heap exhaustion, -XX:+HeapDumpOnOutOfMemoryError can capture a heap dump; for GC evidence, use unified logging such as -Xlog:gc*. NMT can help with native-memory investigation when it was enabled at startup. The legacy -XX:+PrintGCDetails and -XX:+PrintGCTimeStamps flags are replaced by unified logging on current JDKs.

Further Reading

Conclusion

The -X and -XX namespaces expose implementation-specific HotSpot options for heap sizing, garbage collection, JIT behavior, and diagnostics. Their names and defaults can change across releases, vendors, and collectors, so confirm support against the exact runtime you deploy.

Measure before tuning. Record a baseline, make one change tied to a specific symptom, compare under the same workload, and keep a rollback path. In containers, budget for the entire process rather than assigning the full memory limit to the Java heap.

Category

Related Posts

Java Flight Recorder: Continuous Monitoring and Diagnostics

Learn Java Flight Recorder setup, storage limits, overhead measurement, and practical analysis with Oracle JDK 25 and JMC 9.1.2.

#jvm #java #profiling

JVM Stack Walking API: Fast Stack Traversal and Security Context

A guide to the JVM Stack Walking API showing how to efficiently traverse stack frames, access local variables, and extract security context without the overhead of traditional stack trace capture.

#java #jvm #stack-walking

Deoptimization Debugging: When JIT Compiled Code Reverts

Learn what causes the JVM to deoptimize JIT-compiled code, how to detect deoptimization events, and how to fix the underlying issues.

#jvm #jit #deoptimization