Debugging
suggest changeDebugging Java code usually means answering one of a few questions: where did it fail, what were the values at that point, and what is the program doing right now. The JDK ships tools for all three, and they work the same way on a laptop and on a production server.
This article is a practical tour of those tools. For a detailed explanation of the stack trace format, chained exceptions and printStackTrace(), see Creating and reading stacktraces.
Start with the stack trace
An uncaught exception prints the exception class, its message and the chain of method calls that led to it:
Exception in thread "main" java.lang.IllegalStateException: order 42 has no items
at shop.OrderService.total(OrderService.java:31)
at shop.OrderService.checkout(OrderService.java:18)
at shop.Main.main(Main.java:9)
Caused by: java.lang.ArithmeticException: / by zero
...
Tips for reading it:
- the top frame is where the exception was thrown; the frames below are the callers
- skip framework frames (
java.base/..., Spring, servlet containers) and find the first frame in your code - always read the
Caused by:sections; the lastCaused by:is usually the root cause ... 12 moremeans the remaining frames are identical to the enclosing trace
When you catch and rethrow, pass the original exception as the cause (throw new MyException("context", e)) so this information is not lost.
Helpful NullPointerException messages
Since Java 14 (enabled by default since Java 15) the JVM explains exactly which expression was null:
record Address(String city) {}
record User(String name, Address address) {}
User u = new User("bob", null);
System.out.println(u.address().city().length());
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Npe$Address.city()" because the return value of "Npe$User.address()" is null
at Npe.main(Npe.java:6)
Local variable names appear only if the class was compiled with debug info (javac -g). Without it you get "<local1>" instead of "s". Maven and Gradle compile with -g by default.
Debugging in an IDE
For day-to-day work, the IDE debugger (IntelliJ IDEA, Eclipse, VS Code with the Java extension pack) is the most productive tool. The core features are the same everywhere:
- Breakpoint: click in the gutter next to a line; run the program in Debug mode and execution pauses there
- Conditional breakpoint: pause only when an expression is true, e.g.
order.getId() == 42. Essential inside loops - Exception breakpoint: pause when a given exception type is thrown, even if it is caught later. Great for finding where an exception is swallowed
- Logpoint / tracepoint: a breakpoint that prints a message instead of pausing, a
printlnyou don't have to commit - Step over (execute the current line), step into (enter the called method), step out (finish the current method), resume
- Variables / Watches: inspect locals and fields; Evaluate expression runs arbitrary Java code in the paused frame
- Drop frame / reset frame: re-run the current method from the start (side effects are not undone)
- HotSwap: after editing a method body, recompile and the JVM reloads it without restarting. Changing method signatures or adding fields is not supported by standard HotSpot
Behind the scenes the IDE starts the JVM with the JDWP agent and connects to it, exactly like remote debugging described below.
jdb: the command-line debugger
jdb comes with the JDK. It is handy on a server without a GUI or for quick checks. Compile with -g to get local variables:
public class Calc {
static int sum(int[] xs) {
int total = 0;
for (int x : xs) {
total += x;
}
return total;
}
public static void main(String[] args) {
int[] data = {1, 2, 3};
System.out.println(sum(data));
}
}
$ javac -g Calc.java
$ jdb -classpath . Calc
> stop at Calc:5
Deferring breakpoint Calc:5.
It will be set after the class is loaded.
> run
Breakpoint hit: "thread=main", Calc.sum(), line=5 bci=22
5 total += x;
main[1] locals
Method arguments:
xs = instance of int[3] (id=460)
Local variables:
total = 0
x = 1
main[1] print total + x
total + x = 1
main[1] where
[1] Calc.sum (Calc.java:5)
[2] Calc.main (Calc.java:12)
main[1] dump xs
xs = {
1, 2, 3
}
main[1] clear Calc:5
Removed: breakpoint Calc:5
main[1] cont
6
Most useful commands:
| Command | Meaning |
|---|---|
stop at Class:line |
breakpoint on a line |
stop in Class.method |
breakpoint at method entry |
catch java.io.IOException |
break when the exception is thrown |
run / cont |
start / continue execution |
step, next, step up |
step into, step over, step out |
locals, print expr, dump obj |
inspect values |
set var = value |
change a variable |
where, threads, thread <id> |
stack of the current thread, list threads, switch thread |
clear Class:line |
remove a breakpoint (clear alone lists them) |
Remote debugging with JDWP
To debug a JVM that runs elsewhere (a server, a container, a process started by a script), start it with the JDWP agent:
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 -jar app.jar
Listening for transport dt_socket at address: 5005
transport=dt_socket: communicate over TCPserver=y: the JVM listens and the debugger connects to itsuspend=ymakes the JVM wait for a debugger before runningmain, useful for debugging startup code;suspend=nstarts immediatelyaddress=*:5005listens on all interfaces;address=5005(since Java 9) listens on localhost only
Then attach from the IDE (a Remote JVM Debug / Attach run configuration pointing at host and port 5005) or from jdb:
jdb -connect com.sun.jdi.SocketAttach:hostname=localhost,port=5005
On Linux and macOS the shorter jdb -attach 5005 also works; on Windows -attach defaults to the shared-memory transport, so use the -connect form.
Security: anyone who can reach the JDWP port can run arbitrary code inside your JVM. Never expose it on a public network. Prefer address=5005 (localhost) combined with an SSH tunnel: ssh -L 5005:localhost:5005 server. In Docker, publish the port explicitly with -p 5005:5005 and bind to *:5005 inside the container.
Thread dumps: what is the program doing?
When a program hangs, is slow or uses 100% CPU, a thread dump shows the stack of every thread. First find the process id with jcmd (or jps):
$ jcmd -l
700 Busy
13248 jdk.jcmd/sun.tools.jcmd.JCmd -l
Then take a dump:
jcmd 700 Thread.print # add -l to include java.util.concurrent locks
jstack -l 700 # older tool, same output
kill -3 700 # Unix: dump is printed to the program's stdout
"worker" #28 [12264] prio=5 os_prio=0 cpu=0.00ms elapsed=12.29s tid=0x0000018f0a32cfb0 nid=12264 waiting on condition
java.lang.Thread.State: TIMED_WAITING (sleeping)
at java.lang.Thread.sleep(java.base@25.0.4.1/Thread.java:540)
at Busy.lambda$main$0(Busy.java:4)
- locked <0x000000062801ecb0> (a java.lang.Object)
What to look for:
- threads in
BLOCKEDstate,waiting to lock <0x...>and which thread holds that lock Found one Java-level deadlock:at the end of the dump, printed automatically when the JVM detects a deadlock- threads in
RUNNABLEstate in your code; take 3-4 dumps a few seconds apart and see which stacks stay the same (a poor man's profiler)
Name your threads (new Thread(runnable, "order-worker") or a custom ThreadFactory) so dumps are readable.
With many virtual threads (Java 21+), Thread.print doesn't show them all; use jcmd <pid> Thread.dump_to_file -format=json threads.json instead.
Heap dumps: where did the memory go?
For OutOfMemoryError or a heap that keeps growing, capture a heap dump and open it in Eclipse MAT, VisualVM or IntelliJ IDEA:
jcmd 700 GC.heap_dump /tmp/heap.hprof # live objects only; add -all for everything
jcmd 700 GC.class_histogram | head -20 # quick look without a full dump
Better: let the JVM write a dump automatically at the moment of failure:
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps/ -jar app.jar
java.lang.OutOfMemoryError: Java heap space
Dumping heap to /var/dumps/java_pid8123.hprof ...
Heap dump file created [64505963 bytes in 0.144 secs]
Add -XX:+ExitOnOutOfMemoryError so a process in a broken state exits and gets restarted by its supervisor. In the analyzer, look at the dominator tree / retained size: a leak is usually one collection (a cache, a static map, a listener list) holding millions of objects.
Heap dumps contain all data in memory, including passwords and personal data; treat them as sensitive.
Other jcmd commands worth knowing
jcmd <pid> help lists everything the JVM supports. A few useful ones:
| Command | Shows |
|---|---|
VM.flags |
JVM flags in effect (heap size, GC) |
VM.system_properties |
system properties |
VM.command_line |
how the process was started |
GC.heap_info |
heap usage per generation |
JFR.start duration=60s filename=rec.jfr |
start a Java Flight Recorder recording |
Java Flight Recorder is a low-overhead profiler built into the JVM, safe to use in production. You can also start it at launch with -XX:StartFlightRecording=duration=60s,filename=rec.jfr, then view the file in JDK Mission Control or with jfr print rec.jfr / jfr summary rec.jfr.
Logging and print debugging
A debugger shows a single moment; logs show what happened over time, including in production where you can't pause the process. Use a logging framework (see the Logging chapter) rather than System.out.println:
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
log.debug("computing total for order {} with {} items", order.getId(), items.size());
try {
process(order);
} catch (IOException e) {
// pass the exception as the last argument so the stack trace is logged
log.error("failed to process order {}", order.getId(), e);
}
Leave debug statements in the code and enable them when needed by changing the logger level for one package, instead of adding and removing println calls.
For quick throwaway debugging, System.err.println is fine, and Thread.dumpStack() prints the current call stack without throwing anything: useful to find out who calls a method.
Assertions
Assertions document and check internal invariants. They are disabled by default and enabled with -ea (-enableassertions):
assert balance >= 0 : "negative balance: " + balance;
java -ea -jar app.jar # enable for application classes
java -ea:com.example... -jar app.jar # only for one package and its subpackages
An enabled, failing assertion throws AssertionError with your message, pointing directly at the broken invariant instead of a symptom much later. Don't use assert to validate arguments or user input, since it can be turned off; use Objects.requireNonNull or explicit checks that throw IllegalArgumentException.
A debugging checklist
- Read the whole stack trace, including every
Caused by: - Reproduce the problem reliably, ideally in a small unit test
- Put a breakpoint (or an exception breakpoint) at the failure and inspect state; walk up the stack to see where the bad value came from
- If the problem only happens elsewhere, attach remotely via JDWP or add targeted
debuglogging - For hangs take several thread dumps; for memory problems take a heap dump
- Once fixed, keep the reproducing test so the bug doesn't come back