Java monitoring in production: what to measure in the JVM, from heap and GC to threads, pools and virtual threads

Which JVM signals actually predict outages, how to read heap, garbage collection and thread metrics, how to instrument Java with the OpenTelemetry agent, and which alerts are worth waking up for.

Obseria TeamObseria
Summary
  • Java monitoring in production combines per-endpoint latency and errors with JVM internals: heap and non-heap memory, garbage collection pauses and overhead, thread states, CPU and connection pools.
  • The OpenTelemetry Java agent adds traces and runtime metrics such as jvm.memory.used and jvm.gc.duration without code changes, while Micrometer and Spring Boot Actuator are a solid alternative for metrics.
  • Container-aware memory settings, heap dumps on OutOfMemoryError and JDK Flight Recorder for continuous profiling turn a vague memory or latency problem into a concrete cause.

Java monitoring in production means watching two things at once: what your users experience, measured as latency and errors per endpoint, and what the Java Virtual Machine does underneath, from heap usage and garbage collection to threads and connection pools.

This guide explains what to monitor in a Java application, layer by layer, covers what changes with virtual threads and containers, shows how to instrument Java with the OpenTelemetry agent or Micrometer, and ends with a metrics table, example alerts and a JVM monitoring checklist you can copy.

Start with requests: latency and errors per endpoint

The JVM is a means to an end. The first layer of Java application performance monitoring is the same as for any service: request rate, error rate and duration for every HTTP route, gRPC method or message listener.

  • Group by route template. Use /orders/{id}, not the raw URL, so that metrics stay low in cardinality and comparable over time.
  • Use percentiles. Track p50, p95 and p99. In the JVM, a tail of slow requests is often caused by GC pauses or by threads waiting for a pool connection, which an average hides. Our glossary entry on percentiles explains why p99 matters.
  • Separate error classes. HTTP 5xx, uncaught exceptions, timeouts and rejected tasks from a full executor are different failure modes. Error tracking that groups exceptions by stack trace shows which one is new after a deploy.

JVM monitoring of heap and non-heap memory

The heap holds your objects and is managed by the garbage collector. Non-heap memory holds class metadata (Metaspace), the JIT code cache, thread stacks and direct byte buffers. Both can run out, with different symptoms.

  • Heap used versus max: heap usage always rises and falls in a sawtooth pattern. The meaningful number is the heap used after a collection. If that floor keeps rising over hours or days, you are probably looking at a memory leak.
  • Old generation occupancy: in generational collectors, long-lived objects end up in the old generation. Steady growth there is the earliest leak indicator.
  • Metaspace: grows with the number of loaded classes. Continuous growth often points to class loader leaks, for example from repeated redeploys in an application server or heavy use of dynamically generated proxies.
  • Direct buffers and code cache: Netty-based servers and NIO clients allocate off-heap buffers. A full code cache makes the JIT stop compiling and degrades performance silently.

OpenTelemetry reports these values as jvm.memory.used, jvm.memory.committed, jvm.memory.limit and jvm.memory.used_after_last_gc, each with the attributes jvm.memory.pool.name and jvm.memory.type (heap or non_heap). These metrics are stable in the semantic conventions.

Garbage collection: pause times, frequency and overhead

Garbage collection is where JVM performance problems most often become visible. Three measurements matter:

  • Pause time: how long application threads are stopped. Track the maximum and p99 per collector, not only the average.
  • Frequency: how often collections run. Young collections every few seconds are normal; frequent full or mixed collections are not.
  • GC overhead: the share of wall-clock time spent in GC. When it climbs into double-digit percentages, the application is spending its time collecting instead of serving requests, usually shortly before an OutOfMemoryError.

OpenTelemetry records each collection in the histogram jvm.gc.duration (in seconds) with the attributes jvm.gc.name and jvm.gc.action. The sum over a time window divided by the window length gives you GC overhead; the count gives you frequency.

Which collector you are running

G1 is the default collector on server-class machines since JDK 9 and balances throughput and pause times. For latency-sensitive services, OpenJDK offers two low-pause collectors that do most of their work concurrently:

  • ZGC (-XX:+UseZGC): production-ready since JDK 15. Generational ZGC arrived in JDK 21, became the default mode in JDK 23, and the non-generational mode was removed in JDK 24.
  • Shenandoah (-XX:+UseShenandoahGC): production-ready since JDK 15, available in many but not all OpenJDK builds. A generational mode was added experimentally in JDK 24 and became a product feature in JDK 25.

Low-pause collectors change what you watch. Pauses become short, so the more important signals are allocation rate, concurrent cycle duration and allocation stalls, where application threads have to wait because the collector cannot keep up. Note that the JVM may also choose Serial GC on small containers with less than two CPUs or less than about 1.8 GB of memory, so always check which collector is actually active.

Threads, CPU and class loading

Thread metrics show whether work is flowing or stuck. jvm.thread.count is broken down by jvm.thread.state, which makes the following patterns visible:

  • Many BLOCKED threads: lock contention on a synchronized block or a shared resource.
  • Many WAITING or TIMED_WAITING threads in a request pool: threads waiting on a downstream call, a connection pool or a queue.
  • Steadily rising total thread count: a thread leak, for example executors created per request and never shut down.

For executor-based thread pools, track active threads, queue size and rejected tasks. A pool whose queue grows while all threads are busy is the Java equivalent of a saturated worker pool. A thread dump (jcmd <pid> Thread.print) taken during an incident shows exactly where threads are stuck.

For CPU, jvm.cpu.recent_utilization and jvm.cpu.time show how much the JVM process uses, and jvm.cpu.count shows how many processors the JVM believes it has, which matters in containers. Class loading (jvm.class.loaded, jvm.class.unloaded, jvm.class.count) is usually flat after startup; continuous growth goes hand in hand with Metaspace growth.

Connection pools: HikariCP metrics

Most Spring Boot applications use HikariCP for JDBC connections. When the pool is exhausted, request threads wait for a connection until connectionTimeout (30 seconds by default) expires, and latency explodes without any error in the database itself. Watch:

  • Active, idle and total connections against the configured maximumPoolSize.
  • Pending threads: threads waiting for a connection. In a healthy pool this is zero almost all the time.
  • Acquire time and connection timeouts: how long it takes to get a connection and how often that fails.
  • Usage time: how long connections are held.

With Micrometer, HikariCP publishes these as hikaricp.connections.active, hikaricp.connections.pending, hikaricp.connections.acquire and hikaricp.connections.timeout. The OpenTelemetry agent instruments HikariCP using the database connection pool semantic conventions, for example a connection count by state; the exact metric names depend on the agent version and its semantic convention settings.

Virtual threads (Java 21+) and container awareness

What virtual threads change

Virtual threads became final in JDK 21. They are cheap, so an application can run hundreds of thousands of them, and request-per-thread code no longer needs a large platform thread pool. For monitoring, this means:

  • Thread count loses its meaning as a saturation signal. Platform thread metrics do not count virtual threads. Watch the bottleneck that remains instead: connection pools, semaphores and downstream rate limits.
  • Pinning matters. A virtual thread pinned to its carrier thread blocks that carrier. Before JDK 24, blocking inside synchronized caused pinning; JDK 24 removed that limitation, while native calls can still pin. JFR records the event jdk.VirtualThreadPinned.
  • Thread dumps need a new format. Use jcmd <pid> Thread.dump_to_file -format=json <file> to include virtual threads.

Containers and memory limits

Modern JVMs detect container CPU and memory limits. By default, the maximum heap is 25 percent of the available memory, which wastes most of a container's memory. Set the heap as a percentage instead of a fixed -Xmx, and leave room for Metaspace, thread stacks, direct buffers and the agent:

# Example JVM flags for a container with a 2 GiB memory limit
-XX:MaxRAMPercentage=70.0
-XX:+HeapDumpOnOutOfMemoryError
-XX:HeapDumpPath=/dumps
-XX:+ExitOnOutOfMemoryError
-Xlog:gc*:file=/logs/gc.log:time,uptime,level,tags:filecount=5,filesize=10m

If the total process memory exceeds the container limit, the kernel kills the process from outside; you will see an OOM kill with exit code 137 and no Java stack trace. That is a different problem from a Java OutOfMemoryError and needs a different fix: more headroom for non-heap memory, not a larger heap.

OutOfMemoryError, heap dumps and JDK Flight Recorder

An OutOfMemoryError message tells you which area ran out: Java heap space, Metaspace, Direct buffer memory or GC overhead limit exceeded. With -XX:+HeapDumpOnOutOfMemoryError, the JVM writes an .hprof file you can open in Eclipse MAT or VisualVM to find the dominator objects holding the memory. You can also trigger a dump on demand with jcmd <pid> GC.heap_dump /dumps/heap.hprof. Make sure the dump path is on a persistent volume and has space for a file about the size of the heap, and treat dumps as sensitive data because they contain everything in memory, including personal data.

JDK Flight Recorder (JFR) is built into the JVM and records events such as allocations, lock contention, GC phases, I/O and CPU samples with low overhead. Starting it at launch keeps a rolling recording you can dump after an incident:

-XX:StartFlightRecording=name=continuous,settings=default,maxage=6h,disk=true
# later, on demand:
jcmd <pid> JFR.dump name=continuous filename=/dumps/incident.jfr

Continuous profiling goes one step further: it collects CPU and allocation profiles all the time and links them to services and deploys, so you can compare the hot methods before and after a release instead of reproducing the problem.

Instrumentation: OpenTelemetry Java agent, Micrometer and logs

OpenTelemetry Java agent

The OpenTelemetry Java agent is the fastest route to zero-code instrumentation: you attach it with -javaagent and it instruments Spring, servlet containers, JDBC, HTTP clients, Kafka, gRPC and many other libraries, and emits the JVM runtime metrics described above. JAVA_TOOL_OPTIONS is a convenient way to add it in containers without changing the start command:

JAVA_TOOL_OPTIONS="-javaagent:/otel/opentelemetry-javaagent.jar"
OTEL_SERVICE_NAME=checkout-service
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production,service.version=1.42.0
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.2

The agent exports traces, metrics and logs over OTLP, so you get distributed tracing across services.

Micrometer and Spring Boot Actuator

If you already use Spring Boot, Actuator with Micrometer exposes JVM, HikariCP, executor and HTTP server metrics out of the box (jvm.memory.used, jvm.gc.pause, http.server.requests), either as a Prometheus endpoint or through an OTLP registry. Micrometer is a good choice for metrics and custom business counters; combine it with the agent or Micrometer Tracing for traces.

Structured logs with trace IDs

Logs become much more useful when every line carries the trace ID. The OpenTelemetry agent injects trace_id, span_id and trace_flags into the Logback and Log4j2 MDC; a JSON encoder then writes them as fields.

Metrics table, example alerts and a JVM monitoring checklist

The thresholds below are starting points for illustration, not universal values. Tune them to your service and its SLOs.

MetricWhy it mattersExample alert
p99 latency per routeDirect measure of user experiencep99 above SLO target for 10 min
Error rate per routeFailed requests, new exceptions after deploys5xx rate above 1 % for 5 min
Heap used after GC (jvm.memory.used_after_last_gc)Leak indicator, OOM early warningAbove 85 % of heap limit for 15 min
GC overhead (from jvm.gc.duration)Time not spent serving requestsAbove 10 % over 5 min
Max GC pauseCauses latency spikes and timeoutsSingle pause above 500 ms (G1 example)
Metaspace usedClass loader leaksContinuous growth over 24 h
Threads by state (jvm.thread.count)Contention, stuck threads, thread leaksBLOCKED threads above 20 for 5 min
Executor queue and rejectionsSaturation of request processingAny rejected tasks
HikariCP pending threadsPool exhaustion before database errorsPending above 0 for 2 min
HikariCP connection timeoutsRequests failing on pool waitAny increase
Container memory vs. limitOOM kill risk from non-heap growthAbove 90 % of limit
JVM restarts / exit code 137Crashes and OOM killsMore than 1 restart in 30 min

JVM monitoring checklist

  • Request rate, error rate and p50/p95/p99 latency per route template
  • OpenTelemetry Java agent attached via JAVA_TOOL_OPTIONS, or Micrometer with Actuator
  • service.name, environment and version set as resource attributes
  • Heap, old generation, Metaspace, code cache and direct buffers collected
  • Heap used after GC tracked as the leak indicator
  • GC pause time, frequency and overhead per collector; active collector verified
  • Threads by state, executor queue sizes and rejected tasks
  • HikariCP active, idle, pending, acquire time and timeouts
  • -XX:MaxRAMPercentage set, with headroom for non-heap memory
  • -XX:+HeapDumpOnOutOfMemoryError with a persistent, access-restricted dump path
  • GC logging and a rolling JFR recording enabled
  • Virtual thread pinning checked via JFR on JDK 21+
  • Logback or Log4j2 writing JSON with trace_id and span_id
  • Container OOM kills and restarts alerted separately from Java OOMs
  • Deploy markers on all dashboards

Many of the same principles apply to other runtimes; our PHP monitoring guide shows how they translate to a request-per-process model.

How Obseria helps with Java monitoring

Obseria is an OpenTelemetry-native observability platform, so the OpenTelemetry Java agent, Micrometer OTLP export and JSON logs described above work without a proprietary agent. The Java integration brings JVM runtime metrics, traces, logs and profiles from the same service together.

  • Obseria Pipeline filters, samples and masks personal data in Java telemetry before it is stored in the EU.
  • Continuous profiling and error tracking connect a GC or CPU regression to the methods and deploy behind it.
  • Obseria Intelligence correlates heap growth, an exhausted connection pool and a recent release into one root cause with evidence.
  • SLOs with burn-rate alerts replace static thresholds for your most important endpoints.

You can connect your first JVM service in minutes with a free Obseria trial.

Share

Observability that delivers answers.

Start for free with OpenTelemetry, no credit card required.