Skip to content
javahacks.dev
Debugging

How to Use Conditional Breakpoints and Logpoints in Java

Stop only where it matters with conditional breakpoints, hit counts and logpoints that print values without pausing, and avoid their performance traps.

6 min read
Summarize in AI
Flat illustration of a stack trace of frames with a bug beside it, with the OpenJDK, Sentry, Spring Boot, IntelliJ IDEA and Apache Maven logos.

A breakpoint in a loop that runs ten thousand times is useless if it stops on every pass. Debuggers have three tools for this: conditions, hit counts and logpoints. They turn a breakpoint from a stop sign into a filter and a probe. The examples use IntelliJ IDEA; the same ideas exist in Eclipse and VS Code with different menu names. The basic workflow is in debugging in IntelliJ IDEA.

Conditional breakpoints

Right-click the red dot and type a Java boolean expression. The program stops only when it is true:

java
for (Order order : orders) {
    process(order);        // breakpoint here, condition: order.total() > 100_000
}

The expression can use any variable in scope and call methods. Common conditions:

GoalCondition
One specific recordorder.id() == 4711
A string value"ana".equals(user.getName())
A null casecustomer == null
Every 1000th iterationi % 1000 == 0
A specific threadThread.currentThread().getName().equals("worker-3")

Write string comparisons with the literal first ("ana".equals(name)) so a null name does not raise a NullPointerException inside the condition. If the condition itself throws, most debuggers stop at the breakpoint and report the error, which can look like the bug you are chasing.

Hit counts

A hit count (called "pass count" in some tools) stops on the Nth time the line runs, or after N times. Use it when you know the failure happens late and cannot write a condition for it: "stop on the 5,000th pass". It is much cheaper than a condition, because the debugger counts without evaluating an expression.

Logpoints

A logpoint prints a message when the line is reached and lets the program continue. In IntelliJ it is "Evaluate and log" in the breakpoint's settings; the "Suspend" option is turned off.

Text
Evaluate and log: "order " + order.id() + " total=" + order.total() + " thread=" + Thread.currentThread().getName()

The output appears in the Debug console. This replaces the cycle of adding a System.out.println, recompiling, running and removing it. Nothing changes in the source. Logpoints suit code that runs in tight loops, code in a framework you cannot edit and any program you cannot afford to pause, such as a service handling live requests in a test environment.

Dependent breakpoints

A breakpoint can be enabled only after another one was hit. Set breakpoint A in the setup of the scenario and B at the place of interest, with B depending on A: B is ignored until A has stopped once. It prevents B from stopping in unrelated paths, such as application start-up.

Suspend only one thread

By default, hitting a breakpoint suspends all threads. In a multi-threaded program that changes the timing and can hide races. Set the breakpoint to suspend only the thread that hit it:

Text
Suspend: Thread

Other threads keep running, and the paused thread waits. Switch threads in the Threads view to see their state. For a deadlock investigation, see deadlocks with thread dumps.

Exception breakpoints with conditions

An exception breakpoint stops where an exception is thrown. Add a condition to narrow it: stop on IllegalArgumentException only when the message contains "customer". Combine with "caught" and "uncaught" options, and with class filters to ignore library packages. This finds the first occurrence of a rarely thrown error without stepping.

Performance traps

A condition is evaluated each time the line is reached, through the debugger interface, which costs microseconds to milliseconds. A loop of a million iterations with a method call in the condition can take minutes. Mitigations:

  • Prefer a hit count when it fits.
  • Move the check into code temporarily (if (order.id() == 4711) { stop(); } with a breakpoint inside) when the program is slow and you can recompile.
  • Use a field access instead of a method call in the condition.
  • Remove conditional breakpoints on hot lines when you are done; they slow every later run.

Practice on a program with a planted bug

Debugging skills are easier to build on code where you know the answer. This program processes a batch of orders and corrupts exactly one of them, the 4,711th, when the total is over a threshold:

java
import java.util.ArrayList;
import java.util.List;

public class BatchDemo {

    record Order(int id, long totalCents, String customer) {}

    public static void main(String[] args) {
        List<Order> orders = new ArrayList<>();
        for (int i = 1; i <= 10_000; i++) {
            orders.add(new Order(i, (i * 37L) % 200_000, i % 50 == 0 ? null : "cust-" + (i % 300)));
        }

        long sum = 0;
        for (Order order : orders) {
            sum += process(order);
        }
        System.out.println("sum = " + sum);
    }

    static long process(Order order) {
        long fee = order.totalCents() / 100;
        if (order.id() == 4711) {
            fee = -fee;                                  // the planted bug
        }
        return order.totalCents() + fee + order.customer().length();   // NPE when customer is null
    }
}

The program fails with a NullPointerException on order 50, the first order with a null customer, so the second bug hides behind the first. Use it to try each tool in this post.

Walking through it with each tool

  1. Exception breakpoint. Add a NullPointerException breakpoint and run. The debugger stops on the first throw, in process, with order visible in the Variables view. You see customer == null without reading a stack trace.
  2. Conditional breakpoint. Put a breakpoint on long fee = ... with the condition order.id() == 4711. The debugger skips 4,710 passes and stops on the one you want. Inspect fee before and after the if.
  3. Hit count. Remove the condition and set the hit count to 4711. It stops on the same pass, and it is faster, because no expression is evaluated.
  4. Logpoint. On the sum += process(order); line, add a logpoint with the message "id=" + order.id() + " total=" + order.totalCents() and a condition order.totalCents() > 190000. The console prints only the large orders, and the program runs to the end without stopping.

Fix the null case with a guard, rerun, and the planted bug shows itself: the sum is smaller than the value you compute by hand, and the logpoint output tells you which order is responsible.

The same ideas without an IDE

Remote servers have no IDE, and the same techniques apply from a terminal. Start the JVM with a debug port, bound to localhost so it is not exposed, and attach with jdb:

Shell
java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005 BatchDemo.java
Shell
ssh -L 5005:127.0.0.1:5005 app-host
jdb -attach 5005
> stop in BatchDemo.process
> cont
> print order
> dump order
> where
> cont

jdb has no condition syntax of its own, so for a hot method you combine stop in with a hit count by counting cont commands, or you fall back to a guard in code. Never open the debug port on a public interface: JDWP gives full control of the process to whoever connects, and it has no authentication. Close the port when you are done, which means restarting the process without the agent.

A guard in code when the debugger is too slow

When a method runs millions of times and the debugger's condition evaluation is the bottleneck, move the condition into the program for the session of the investigation:

java
static long process(Order order) {
    if (order.id() == 4711) {
        System.out.println("reached 4711");     // put a breakpoint on this line, no condition
    }
    // ...
}

The breakpoint sits on a line that is only reached when the guard is true, so the debugger evaluates nothing on the other passes. Remove the guard before committing. A checked-in diagnostic guard is a bug report for the next person.

Breakpoints in lambdas and streams

Stream pipelines are awkward to step through, because the work of one line spans many internal frames. Put the breakpoint inside the lambda, and use the stream debugger in IntelliJ (the "Trace Current Stream Chain" button) to see each stage's input and output. A cheaper alternative is peek with a logpoint:

java
orders.stream()
      .filter(o -> o.totalCents() > 190_000)
      .peek(o -> log.debug("candidate {}", o.id()))       // logpoint or log line here
      .map(BatchDemo::process)
      .reduce(0L, Long::sum);

Use peek only for diagnostics: the documentation says it exists to support debugging, and relying on it for side effects in production code is fragile.

Where this does not apply

Breakpoints change timing. For race conditions, add logging instead. In production, attach tools such as jcmd rather than a debugger: jcmd, jstack and jmap. The IntelliJ IDEA breakpoints documentation describes each option, and the JDWP specification defines how debuggers talk to the JVM.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.