Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install java-diagnostics@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin java-diagnostics v1.0.0 follows the Agent Plugins spec.
gh skills-hub install java-diagnostics Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/java-diagnostics/ Extract the ZIP to .github/skills/ in your repo. The folder name must match java-diagnostics for Copilot to auto-discover it.
Skill Files (9)
SKILL.md 7.2 KB
---
name: java-diagnostics
description: 'Symptom-first runtime diagnostics for JVM applications using JDK tools: jcmd, jstack, jmap, jstat, JFR, GC logs, async-profiler, Native Memory Tracking, and Eclipse MAT. Use when a Java app has high CPU, memory leaks or OutOfMemoryError, slow startup, deadlocks or thread starvation, long GC pauses, native memory growth, or slow requests. Includes permission tiers for safe use.'
---
# Java Diagnostics
Pick the lightest tool that answers the question, starting from the symptom.
## Permission tiers (obey them)
| Tier | Tools | Rule |
|------|-------|------|
| 1. Read-only | `jps -l`, `jcmd <pid> help/VM.version/VM.flags/Thread.print`, `jstat`, `jstack`, reading logs | May run after stating the exact command. Class histograms (`jcmd <pid> GC.class_histogram`, `jmap -histo`, `jmap -histo:live`) are NOT Tier 1: they run heap inspection at a safepoint and can pause application threads on a large heap, so treat them as Tier 2 (consent, stated overhead). The default forms and `-histo:live` additionally force a full GC; `-all=true` / `jmap -histo` skip the full GC but still pause during the scan (and count unreachable objects). |
| 2. Recording / attach | JFR (`JFR.start`, `-XX:StartFlightRecording`), async-profiler, NMT (`-XX:NativeMemoryTracking`), enabling GC logs | Requires user consent. State duration and expected overhead (JFR default profile is about 1-2%; async-profiler depends on mode; NMT summary roughly 5-10%, detail more) before running. |
| 3. Intrusive / sensitive | Heap dumps (`GC.heap_dump`, `jmap -dump`), `jhsdb`, commands that print JVM arguments or system properties (`jps -v/-lv/-m`, bare `jcmd`, `VM.system_properties`, `VM.command_line`, `jinfo`, `ps aux` on a Java process; they can expose secrets, redact output), JDWP with suspend, anything on production | Requires explicit consent, a stated target path, free-disk check (a dump is about the size of the used heap), and a stated pause. Heap dumps contain secrets (passwords, tokens, personal data). Never share or upload them; redaction is NOT a reliable safeguard. Analyze locally and delete afterwards. |
Never run Tier 2 or Tier 3 commands against production unless the user explicitly instructs it. Run diagnostic tools as the same OS user as the target JVM. Prefer reproducing on dev or staging.
## Decision table
| Symptom | First step | Then | Reference |
|---------|-----------|------|-----------|
| High CPU | Thread dumps x3 (Tier 1) + `top -H` to map hot native thread ids to `nid` | JFR or async-profiler CPU flame graph (Tier 2) | [threads](references/thread-dumps.md), [jfr](references/jfr.md), [async-profiler](references/async-profiler.md) |
| Memory leak / OOM | `jstat -gcutil`, `GC.class_histogram -all=true` twice, minutes apart (Tier 2: safepoint pause even with `-all=true`; without it a full GC too; get consent on production) | Heap dump + Eclipse MAT (Tier 3) or JFR OldObjectSample (Tier 2) | [heap](references/heap.md), [gc](references/gc.md) |
| Slow startup | `-Xlog:class+load`, framework startup/condition reports, timestamped logs | JFR from start, async-profiler wall-clock | [jfr](references/jfr.md), [async-profiler](references/async-profiler.md) |
| Deadlock / thread starvation | `jcmd <pid> Thread.print` (reports deadlocks), compare dumps over time | Virtual threads: `Thread.dump_to_file` | [threads](references/thread-dumps.md) |
| GC pauses | GC log (`-Xlog:gc*`) and `jstat -gc` | JFR GC events; tune collector/heap | [gc](references/gc.md) |
| Native memory growth (RSS grows, heap does not) | Compare RSS vs heap; enable NMT, `jcmd VM.native_memory baseline` / `summary.diff` (Tier 2) | async-profiler `nativemem` or allocator tools | [nmt](references/native-memory.md), [containers](references/containers.md) |
| Slow requests | Tracing/metrics and logs first; Actuator or Dev UI (see below) | JFR (socket/file/lock events), async-profiler wall-clock | [jfr](references/jfr.md), [async-profiler](references/async-profiler.md) |
| JVM crash / hang, no tools respond | `hs_err_pid*.log`, core dump | `jhsdb` (Tier 3) | [basics](references/jcmd-basics.md) |
Start with [jps/jcmd basics](references/jcmd-basics.md) to identify the target JVM and confirm which JDK version is running.
## Workflow
1. Capture the symptom precisely (when, how often, since which change, JDK version, container limits).
2. Choose the tier needed; state the command, its overhead, and output location, and get consent for Tier 2/3.
3. Collect data to a dedicated directory, with timestamps. Prefer several samples over one.
4. Form a hypothesis from the data, then confirm with a second source (for example a thread dump plus a flame graph).
5. Fix, re-measure with the same method, and clean up artifacts (dumps, recordings).
## Application-level insights (optional)
JDK tools see the JVM; some questions (which endpoint, which SQL query, which bean) are easier at the application level. Optional options, in order of preference:
- **Spring Boot Actuator** (`metrics`, `health`, `loggers`, `httpexchanges`) and **Quarkus Dev UI** / Micrometer metrics are built in and need no extra tool. Expose Actuator endpoints minimally; For `heapdump` and `threaddump`, follow the policy in the `spring-observability` skill: never expose them over public HTTP; the only exception is a temporary, user-consented window with authentication, TLS and network restriction, removed afterwards.
- **BootUI** (https://github.com/jdubois/boot-ui , https://www.julien-dubois.com/boot-ui/): a local-only developer console with an opt-in MCP server for Spring Boot and Quarkus. Optional. Its skill can be installed with `gh skill install jdubois/boot-ui skills/bootui`.
If considering BootUI:
- Ask the user for consent before adding any dependency or installing the skill.
- Use it in a local/dev profile only; never expose it on a network, and never enable its heap dump, thread dump endpoints or MCP server in production.
- Check the capability and version first (read its README for the supported Spring Boot / Quarkus versions) instead of assuming features.
Follow the project's own documentation for usage; this skill does not reproduce it.
## Containers
See [containers](references/containers.md) for attaching tools inside containers, `-XX:MaxRAMPercentage`, and cgroup memory limits.
## References
- [jps / jcmd basics](references/jcmd-basics.md)
- [Thread dumps and deadlocks](references/thread-dumps.md)
- [Heap, histograms, Eclipse MAT](references/heap.md)
- [GC logs and jstat](references/gc.md)
- [JFR and JDK Mission Control](references/jfr.md)
- [async-profiler](references/async-profiler.md)
- [Native Memory Tracking](references/native-memory.md)
- [Containers](references/containers.md)
- Debugger-based investigation: the `java-debugging` skill.
Official docs (prefer them over this skill for the JDK in use; change `21` to your version): `jcmd` <https://docs.oracle.com/en/java/javase/21/docs/specs/man/jcmd.html>, `jfr` <https://docs.oracle.com/en/java/javase/21/docs/specs/man/jfr.html>, JFR guide <https://docs.oracle.com/en/java/javase/21/jfr/introduction-jdk-flight-recorder.html>, troubleshooting guide <https://docs.oracle.com/en/java/javase/21/troubleshoot/>, async-profiler releases <https://github.com/async-profiler/async-profiler/releases>.
async-profiler.md 3.0 KB
# async-profiler (Tier 2: needs consent)
Low-overhead sampling profiler (CPU, wall-clock, allocation, lock, native memory) producing flame graphs. Project: https://github.com/async-profiler/async-profiler . Download a **pinned release** from its GitHub Releases page and verify the checksum (the release API lists a sha256 digest per asset); do not pipe scripts into a shell. State the profiling duration and mode before running. Check the README of the version you use for current flags. The commands below were run against 4.5 (macOS build attached to a running JDK 27 JVM, and the `linux-arm64` build attached to a JDK 21 JVM in an `eclipse-temurin:21` container); `nativemem` needs 4.0 or newer, and `-e lock` prints "No samples were collected" when there is no contention.
## Usage (3.x/4.x launcher `asprof`)
```bash
asprof -d 30 -e cpu -f /secure/dir/cpu.html <pid> # CPU flame graph, 30 s
asprof -d 30 -e wall -t -f wall.html <pid> # wall-clock per thread (slow requests, startup)
asprof -d 30 -e alloc -f alloc.html <pid> # allocations
asprof -d 30 -e lock -f lock.html <pid> # lock contention
asprof -d 60 -e nativemem -f native.html <pid> # native allocations (4.0+); use -f native.jfr then `jfrconv --nativemem --leak` for leak analysis
```
Use as a Java agent for startup profiling:
```
-agentpath:/path/to/libasyncProfiler.so=start,event=cpu,file=/secure/dir/startup.html
```
The report is written when the JVM exits normally (verified: `timeout 5 java -agentpath:...` produced the HTML on SIGTERM).
Open the HTML flame graph in a browser: wide frames at the top are where time goes. Use `wall` for latency (threads blocked on I/O), `cpu` for CPU burn.
## Permissions and caveats
- `cpu` mode on Linux uses `perf_events`. If it fails, check `/proc/sys/kernel/perf_event_paranoid` (needs a low value, or `CAP_PERFMON`/`CAP_SYS_ADMIN`) and `kptr_restrict`. Changing these sysctls is a host-level security change: ask the user, do not do it silently, and do not do it on shared/production hosts. Without them, use `-e ctimer` (4.x docs: like `cpu` but needs no perf_events, no kernel stacks; `-e itimer` is also accepted and ran in 4.5). In 4.5 in a default Docker Desktop container (`perf_event_paranoid=2`, no extra capabilities) plain `-e cpu`, `itimer`, `wall`, `alloc`, `lock`, `nativemem` and the `-agentpath` form all worked without relaxing security, so try the plain command before loosening anything.
- In Docker the default seccomp profile blocks `perf_event_open` (the `--cap-add SYS_ADMIN` / `seccomp=unconfined` variants were not run); running with relaxed security (`--cap-add SYS_ADMIN`, `--security-opt seccomp=unconfined`) weakens isolation: dev only.
- Attach requires the same user as the JVM. macOS support exists with limitations (no perf events).
- Flame graphs can expose class and method names from proprietary code; handle accordingly.
- Debug symbols: enable `-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints` on the target for more accurate attribution (requires a restart).
containers.md 1.7 KB
# Containers
## Memory sizing
- The JVM is container-aware (cgroup limits) in JDK 10+ and 8u191+.
- Heap defaults to 25% of the container limit. Use `-XX:MaxRAMPercentage=75.0` (or lower, e.g. 50-70, if there is significant native/off-heap usage) instead of a fixed `-Xmx`, so the heap scales with the limit.
- Leave headroom for metaspace, thread stacks, code cache, direct buffers; an OOM-kill (exit code 137, `OOMKilled`) with a healthy heap points to native memory growth (see [native-memory](native-memory.md)).
- Verify what the JVM sees: `java -XX:+PrintFlagsFinal -version | grep -E 'MaxHeapSize|MaxRAMPercentage|ActiveProcessorCount'` and `jcmd <pid> VM.flags`.
## Attaching tools
- `jcmd`/`jstack` must run **inside the container** (same PID namespace and user): `docker exec -it <c> jcmd 1 Thread.print`, `kubectl exec <pod> -- jcmd 1 Thread.print`. JRE-only images lack these tools.
- Do not rebuild production images to add tools. Prefer an ephemeral debug container sharing the process namespace (`kubectl debug -it <pod> --image=<jdk-image> --target=<container>`), and only with explicit consent.
- Output files are written by the target JVM inside the container's filesystem; copy them out with `kubectl cp` / `docker cp`, then delete them in the container. Mind ephemeral storage limits for heap dumps.
- Tier 1/2/3 rules apply unchanged; production pods require explicit user instruction.
## CPU
Few CPUs or CFS throttling cause latency and GC thread starvation. Check `-XX:ActiveProcessorCount`, throttling metrics (`container_cpu_cfs_throttled_seconds_total`), and thread-pool sizing.
## Debugging
See the `java-debugging` skill for JDWP port mapping to `127.0.0.1`.
gc.md 1.6 KB
# GC logs and jstat
## Unified GC logging (JDK 9+)
Enabling at startup is a restart, so treat it as Tier 2; overhead is low.
```
-Xlog:gc*=info:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=20m
```
On a running JVM (Tier 2):
```bash
jcmd <pid> VM.log what=gc*=info output=gc.log decorators=uptime,time
jcmd <pid> VM.log list
```
JDK 8 uses `-XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log` instead.
## jstat (Tier 1)
```bash
jstat -gcutil <pid> 1000 10 # utilization %, sampled every 1s, 10 times
jstat -gc <pid> 1000 10 # capacities and sizes in KB
jstat -gccause <pid> 1000 5 # last GC cause
```
Watch: Old (`O`) occupancy after each full/mixed GC. If it keeps ratcheting up, suspect a leak (see [heap](heap.md)). Rising `FGC`/`FGCT` means frequent full GCs.
## Interpreting
- Long pauses: look at pause time per event and the cause (`Allocation Failure`, `Humongous Allocation`, `Metadata GC Threshold`, `System.gc()`).
- Frequent young GCs with high promotion: allocation rate too high or young gen too small.
- Heap near max after GC: heap too small or leak; do not just raise `-Xmx` without checking.
- Pause target: G1 default `-XX:MaxGCPauseMillis=200`; ZGC and Shenandoah target sub-millisecond-class pauses with more CPU/memory overhead. Change one tuning flag at a time and compare logs.
- Tools such as GCeasy or GCViewer can visualize logs, but GC logs may reveal internal hostnames and sizing; do not upload from sensitive environments.
- JFR also records GC events (`jdk.GarbageCollection`, `jdk.GCPhasePause`); see [jfr](jfr.md).
heap.md 3.0 KB
# Heap, histograms, Eclipse MAT
## Tier 2: class histogram (no full GC with `-all=true`, but still a safepoint pause)
```bash
jcmd <pid> GC.class_histogram -all=true | head -40 # no GC; includes unreachable objects
jmap -histo <pid> | head -40 # no GC
jcmd <pid> GC.class_histogram | head -40 # full GC, live objects only
jmap -histo:live <pid> | head -40 # full GC, live objects only
```
All four run heap inspection at a safepoint, which can pause application threads for the duration of the scan on a large heap: on production, get explicit consent and state the overhead first. The last two also force a full GC. The first two avoid the full GC but may count garbage that is not yet collected. Take two histograms several minutes apart under load; classes whose instance count and bytes keep growing are leak suspects.
## Tier 3: heap dump (explicit consent required)
Before running: state the target path, check free disk (`df -h`; roughly the used heap size), and warn of a stop-the-world pause proportional to heap size. Write to a restricted directory (`chmod 700`).
```bash
jcmd <pid> GC.heap_dump /secure/dir/heap.hprof # live objects only (full GC)
jcmd <pid> GC.heap_dump -all=true /secure/dir/heap.hprof # include unreachable objects
```
`jmap -dump:live,format=b,file=heap.hprof <pid>` is the older equivalent. The file is written by the target JVM, so the path must be writable by it (and inside the container if containerized).
**Sensitive data**: a heap dump contains everything in memory: credentials, tokens, session data, personal data. Never upload or share it (including with AI services or issue trackers). Redaction is not a reliable safeguard. Analyze locally and securely delete the file when done.
Automatic dump on OOM (an opt-in startup flag, still Tier 3 because of the data and disk usage):
```
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/secure/dir/
```
Set `HeapDumpPath` to a volume with enough space; in containers an unbounded dump can fill the node.
## Analyze with Eclipse MAT
1. Install Eclipse Memory Analyzer (https://eclipse.dev/mat/) from the official download page. It needs a Java runtime and a heap of about 1.5x the dump size (edit `MemoryAnalyzer.ini`, `-Xmx`).
2. Open the `.hprof`; run the **Leak Suspects** report first.
3. Use the **Dominator Tree** (sorted by retained heap) to find what holds memory.
4. For a suspect object, **Path to GC Roots, excluding weak/soft references** shows why it is not collected.
5. Compare two dumps with the histogram comparison to confirm growth.
6. Common causes: unbounded caches or maps, static collections, listeners never removed, ThreadLocals in pooled threads, classloader leaks on redeploy, large result sets.
Headless parsing is available through `ParseHeapDump.sh` in the MAT distribution (`-vmargs -Xmx...`), producing report ZIPs.
## Alternative (Tier 2)
JFR with `jdk.OldObjectSample` and path-to-gc-roots (`path-to-gc-roots=true`) finds leak candidates without a full dump; see [jfr](jfr.md).
jcmd-basics.md 1.9 KB
# jps and jcmd basics (Tier 1 for the safe commands; see the sensitive-output warning)
```bash
jps -l # list JVMs with PID and main class/JAR only (no arguments)
jcmd <pid> help # commands supported by that JVM
jcmd <pid> VM.version
jcmd <pid> VM.flags # effective -XX flags (no -D properties)
jcmd <pid> VM.uptime
```
Do NOT run these by default: they can print credentials, tokens, connection strings or other secrets passed as `-D` properties or program arguments, and the output lands in the transcript:
- `jps -v`, `jps -lv`, `jps -m`, and bare `jcmd` (without arguments it also prints each JVM's main class and arguments)
- `jcmd <pid> VM.system_properties`, `jcmd <pid> VM.command_line`, `jinfo`, `ps aux` / `ps -ef` / `/proc/<pid>/cmdline` for a Java process
They need user consent first (explicit tier: Tier 3, sensitive output). Prefer reading only the specific property you need (for example `jcmd <pid> VM.system_properties | grep '^java.version'`), and redact secret values before showing or sharing any output.
- Run as the same OS user as the target JVM, on the same host (or inside the same container). Different users/containers fail with "Unable to open socket file" or "process not found".
- `jcmd` is preferred over `jstack`/`jmap`/`jinfo`, which are older single-purpose tools.
- `-XX:+DisableAttachMechanism` blocks attach; `-XX:+StartAttachListener` forces the listener to start.
- Tools must match (or be newer than) the target JDK major version when possible.
## Crash or hang
- A crash writes `hs_err_pid<pid>.log` (path set by `-XX:ErrorFile`). Read the "Problematic frame" and thread sections first.
- `jhsdb` (Tier 3) attaches to a hung process or core file: `jhsdb jstack --pid <pid>` or `jhsdb jstack --exe <java> --core <core>`. It suspends the process while attached and requires matching JDK; core files contain heap data, so treat them like heap dumps.
jfr.md 2.3 KB
# Java Flight Recorder (Tier 2: needs consent)
JFR is built into OpenJDK 11+ (and Oracle JDK 8u262+/OpenJDK 8u262+). Default overhead of the `default` settings is low (about 1% or less); `profile` settings collect more at a few percent. State the duration and settings before starting.
## Start
At startup:
```
-XX:StartFlightRecording=filename=/secure/dir/rec.jfr,duration=120s,settings=profile
```
On a running JVM:
```bash
jcmd <pid> JFR.start name=diag duration=120s settings=profile filename=/secure/dir/rec.jfr
jcmd <pid> JFR.check
jcmd <pid> JFR.dump name=diag filename=/secure/dir/rec.jfr
jcmd <pid> JFR.stop name=diag
```
For a continuous low-overhead recording to dump after an incident, use `maxage=30m maxsize=250m` with `settings=default`, and set `disk=true` limits so storage is bounded.
Leak candidates: add `path-to-gc-roots=true` when dumping (`JFR.dump ... path-to-gc-roots=true`), which includes the `jdk.OldObjectSample` event and costs extra time.
## Analyze (command line)
```bash
jfr summary rec.jfr # event counts
jfr print --events jdk.ExecutionSample rec.jfr | head
jfr print --events jdk.GarbageCollection rec.jfr
jfr print --events jdk.JavaMonitorEnter,jdk.ThreadPark rec.jfr
jfr print --events jdk.VirtualThreadPinned rec.jfr
jfr print --json --events jdk.SocketRead rec.jfr
```
Useful events: `jdk.ExecutionSample` (CPU hot methods), `jdk.ObjectAllocationSample` (allocation), `jdk.GCPhasePause`, `jdk.JavaMonitorEnter` (lock contention), `jdk.SocketRead`/`jdk.FileRead` (slow I/O), `jdk.ClassLoad`, `jdk.CPULoad`, `jdk.NativeMethodSample`.
`jdk.VirtualThreadPinned` (JDK 21+, in the default profile, 20 ms threshold) reports virtual threads that blocked while pinned; verified on JDK 21.0.12 and 27. It is the replacement for `-Djdk.tracePinnedThreads` (JDK 21-23 only, see [thread-dumps](thread-dumps.md)).
## JDK Mission Control
Open the `.jfr` file in JDK Mission Control (JMC, separate download from https://adoptium.net/jmc or the Oracle/Eclipse distributions). The Automated Analysis page gives ranked findings; the Method Profiling, Memory, Lock Instances, and I/O pages drill down. Open recordings locally; they contain stack traces, system properties, and sometimes command lines or environment details, so do not share them from sensitive environments.
native-memory.md 1.5 KB
# Native Memory Tracking (Tier 2: needs consent)
Use when container RSS grows but heap usage does not. NMT tracks JVM-internal allocations (metaspace, thread stacks, code cache, GC structures, direct buffers via `Internal`/`Other`), not arbitrary native library `malloc`.
Enable at startup (needs a restart; Oracle documents a 5-10% JVM performance drop with NMT enabled, plus extra malloc header memory, and `detail` costs more; measure on your workload):
```
-XX:NativeMemoryTracking=summary
```
Then:
```bash
jcmd <pid> VM.native_memory summary
jcmd <pid> VM.native_memory baseline
# ... wait while the problem develops ...
jcmd <pid> VM.native_memory summary.diff
```
Use `detail` only for short sessions (higher overhead). It cannot be enabled on a running JVM.
## Common growth areas
| Category | Typical cause | Mitigation |
|----------|---------------|-----------|
| Thread | Too many threads (stack ~1 MB each) | Bound pools; virtual threads; `-Xss` |
| Class | Classloader leak, dynamic proxies | Fix leak; `-XX:MaxMetaspaceSize` |
| Code | Large JIT code cache | `-XX:ReservedCodeCacheSize` |
| GC | Remembered sets/card tables for big heaps | Right-size heap |
| Internal/Other | Direct `ByteBuffer`, Netty pools | `-XX:MaxDirectMemorySize`, check pooling |
| Not in NMT | JNI/native libraries, glibc arenas | async-profiler `nativemem`; `MALLOC_ARENA_MAX=2`; allocator profiling |
Total RSS ≈ heap + metaspace + threads + code cache + direct buffers + native libs. Compare against the container memory limit (see [containers](containers.md)).
thread-dumps.md 3.3 KB
# Thread dumps and deadlocks (Tier 1)
```bash
jcmd <pid> Thread.print # preferred; includes deadlock report
jcmd <pid> Thread.print -l # also lists ownable synchronizers/locks
jstack <pid> # equivalent older tool
```
Do not use `kill -3 <pid>` / SIGQUIT as an unconditional fallback. On Unix, use it only after verifying that the target JVM has its thread-dump SIGQUIT handler installed and that stdout/stderr are captured. Explicitly exclude JVMs started with `-Xrs` / `-XX:+ReduceSignalUsage`, or with unknown/custom signal handling: without the JVM handler, SIGQUIT can terminate the process and produce a core dump. If signal handling cannot be verified, do not send the signal; resolve the `jcmd`/attach permissions instead. See the [JDK launcher `-Xrs` documentation](https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html) and [Linux signal defaults](https://man7.org/linux/man-pages/man7/signal.7.html).
Take **3 dumps, 5-10 seconds apart**, to see what changes. A single dump is a snapshot, not a trend. Thread dumps include stack frames and thread names, which may contain request data; do not share publicly.
## High CPU: map hot threads
```bash
top -H -p <pid> # find hot native thread ids (decimal)
printf '%x\n' <tid> # convert to hex, match "nid=0x..." in the dump
```
Check whether the hot thread is application code, GC threads (`GC Thread`, `G1 Conc`), or JIT compiler threads (`C2 CompilerThread`).
## Deadlock
`Thread.print` ends with "Found one Java-level deadlock" and lists the lock cycle. Otherwise look for many threads `BLOCKED` on the same monitor (`waiting to lock <0x...>`) whose owner is itself waiting. Thread starvation shows pools with all threads `WAITING`/`TIMED_WAITING` in the same call (e.g., a connection pool `getConnection`, a blocking HTTP call) while the queue grows.
## Virtual threads (JDK 21+)
`Thread.print` does not list virtual threads. Use:
```bash
jcmd <pid> Thread.dump_to_file -format=json threads.json
jcmd <pid> Thread.dump_to_file threads.txt
```
`Thread.print` shows only platform threads (virtual threads were verified missing on JDK 27, present in `Thread.dump_to_file`). Pinned virtual threads (blocked inside `synchronized` on JDK 21-23, or native frames on any version) can be investigated with the JFR event `jdk.VirtualThreadPinned` (see [jfr](jfr.md)). `-Djdk.tracePinnedThreads=full` (or `short`, which prints only the frames holding monitors) works only on JDK 21-23: on 21.0.12 it printed `VirtualThread[#20,vt-pinned]/runnable@ForkJoinPool-1-worker-1 reason:MONITOR` with the stack and `<== monitors:1`. JEP 491 removed it in JDK 24 (verified silent on 27: no output). From JDK 24, `synchronized` no longer pins; pinning remains for native frames and class initializers (a virtual thread sleeping inside a static initializer was reported by JFR on JDK 27 with `pinnedReason = "VM call to Pin$Slow.<clinit> on stack"`). On JDK 21-23 the same JFR event also works (verified on 21.0.12 for the `synchronized` case).
## Reading tips
- States: `RUNNABLE` (on CPU or in native I/O), `BLOCKED` (monitor), `WAITING`/`TIMED_WAITING` (park, sleep, wait).
- `RUNNABLE` in `socketRead0` is usually waiting on the network, not using CPU.
- Group threads by identical top frames to find the dominating pattern.
License (MIT)
View full license text
MIT License Copyright GitHub, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.