Debugging

suggest change

Debugging 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:

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:

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

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:

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

  1. Read the whole stack trace, including every Caused by:
  2. Reproduce the problem reliably, ideally in a small unit test
  3. 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
  4. If the problem only happens elsewhere, attach remotely via JDWP or add targeted debug logging
  5. For hangs take several thread dumps; for memory problems take a heap dump
  6. Once fixed, keep the reproducing test so the bug doesn't come back

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents