Skip to lesson

Debugging a running Spring Boot app

A ShopLite endpoint returns the wrong data, and the code alone does not explain why. The same debugger works on a running Spring Boot app, but requests keep arriving while you are paused.

Running the app in debug mode and hitting a breakpoint with curl

A request thread is the thread that Tomcat uses to run one HTTP request through your controller, service and repository. A breakpoint in that code pauses the thread, so the caller waits.

Start ShopliteApiApplication with Debug, put a breakpoint in ProductService.get, and send the request with curl (Example 1). The request thread pauses, and curl waits for the answer.

Example 1 · Pausing a real request in ShopLite

Runs in: a terminal, with shoplite-api running in debug mode

Terminal
# 1. In the IDE, start ShopliteApiApplication with Debug (gutter icon next to main).#    DB_URL, DB_USER and DB_PASSWORD go in the run configuration's environment variables.# 2. Put a line breakpoint in ProductService.get (line 57).# 3. Send a request from a terminal:curl -i http://localhost:8080/api/v1/products/9
Sample output (port numbers and times will differ)
IntelliJ console, first line of the debug run (the port changes every time):
Connected to the target VM, address: '127.0.0.1:52817', transport: 'socket'

Terminal: curl prints nothing yet. The request thread is paused at ProductService.java:57
$ curl -i http://localhost:8080/api/v1/products/9

After you press Resume in the IDE (IntelliJ F9 / Cmd+Option+R, VS Code F5):
HTTP/1.1 200
Content-Type: application/json
(other headers left out)

{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}

What this code does

  • The paused frame of ProductService.get shows id = 9, and the frames list shows the Tomcat thread with the proxy, controller and Spring MVC frames below it, the same path as a stack trace.
  • curl prints nothing while the thread is paused; after Resume it receives the normal 200 response. Nothing about the request changed, it was only delayed.

Tomcat runs each request on its own thread, named like http-nio-8080-exec-1. In IntelliJ, click the gutter icon next to main → Debug, and set DB_URL, DB_USER and DB_PASSWORD under Run → Edit Configurations → Environment variables. In VS Code, click Debug above main, or press F5, with an env block in .vscode/launch.json.

While the thread is paused, curl simply waits. It gets its answer as soon as you resume.

Order of execution

Pause a real request

Put the steps in the order that pauses a ShopLite request.

Start from the controller method when you do not know where a request goes: the frames list then shows the whole path controller → service → repository as you step into it.

Debugging a failing test

Surefire is the Maven plugin that runs your unit tests in a separate test JVM. With -Dmaven.surefire.debug it starts that JVM with a debug port and waits for a debugger.

A failing test repeats the bug in seconds, without curl or a running app. Example 2 shows a ShopLite test that fails with the same NullPointerException the 500 error showed.

Example 2 · A failing test, then the same test waiting for a debugger

Runs in: the shoplite-api Spring Boot project, with the categoryName experiment from the Stack traces lesson

Java
package com.shoplite.product;
import static org.assertj.core.api.Assertions.assertThat;
import java.math.BigDecimal;
import org.junit.jupiter.api.Test;
import com.shoplite.category.Category;
class ProductMapperTest {
    @Test    void topLevelCategoryIsShownWithoutAParent() {        Category books = new Category("Books", null);        Product cleanCode = new Product("BK-CLEAN", "Clean Code", books, new BigDecimal("499.00"), 30);
        ProductResponse response = ProductMapper.toResponse(cleanCode);
        assertThat(response.categoryName()).isEqualTo("Books");    }
    @Test    void subcategoryIsShownAfterItsParent() {        Category mobiles = new Category("Mobiles", new Category("Electronics", null));        Product redmi = new Product("MOB-RN13", "Redmi Note 13 5G", mobiles, new BigDecimal("17999.00"), 40);
        assertThat(ProductMapper.toResponse(redmi).categoryName()).isEqualTo("Electronics > Mobiles");    }}
Sample output (times will differ)
$ ./mvnw test -Dtest=ProductMapperTest
...
[ERROR] Tests run: 2, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.062 s <<< FAILURE! -- in com.shoplite.product.ProductMapperTest
[ERROR] com.shoplite.product.ProductMapperTest.topLevelCategoryIsShownWithoutAParent -- Time elapsed: 0.015 s <<< ERROR!
java.lang.NullPointerException: Cannot invoke "com.shoplite.category.Category.getName()" because the return value of "com.shoplite.category.Category.getParent()" is null
	at com.shoplite.product.ProductMapper.categoryName(ProductMapper.java:61)
	at com.shoplite.product.ProductMapper.toResponse(ProductMapper.java:55)
	at com.shoplite.product.ProductMapperTest.topLevelCategoryIsShownWithoutAParent(ProductMapperTest.java:18)
	...

$ ./mvnw test -Dtest=ProductMapperTest -Dmaven.surefire.debug
...
[INFO] --- surefire:3.5.6:test (default-test) @ shoplite-api ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
Listening for transport dt_socket at address: 5005

What this code does

  • The first test fails with the same NullPointerException the 500 error showed, in milliseconds and without a database. A plain unit test is enough because ProductMapper has no dependencies.
  • With -Dmaven.surefire.debug the test JVM stops before running anything and prints Listening for transport dt_socket at address: 5005. Attach the IDE (Remote JVM Debug or a VS Code attach configuration) and the test continues to your breakpoint.

Put a breakpoint in the code under test and start the test in debug mode. In IntelliJ, click the gutter icon next to the test method → Debug. In VS Code, use Debug Test above the method or in the Testing view.

From a terminal, -Dmaven.surefire.debug makes Surefire start the test JVM with suspend=y on port 5005: it waits until you attach a debugger. For integration tests run by Failsafe (*IT), the property is -Dmaven.failsafe.debug.

Spring tests (@WebMvcTest, @SpringBootTest) run your controllers and services inside the test JVM, so breakpoints in src/main/java are hit during the test too.

Remote debugging with -agentlib:jdwp on port 5005

JDWP is the Java Debug Wire Protocol: how a debugger talks to a JVM. A JVM started with the -agentlib:jdwp option opens a debug port that an IDE can attach to.

Remote debugging means attaching the IDE's debugger to a JVM that is already running, through a network port. In VS Code, add this attach configuration to .vscode/launch.json:

JSON
{  "version": "0.2.0",  "configurations": [    {      "type": "java",      "name": "Attach to ShopLite (5005)",      "request": "attach",      "hostName": "localhost",      "port": 5005    }  ]}

In IntelliJ, create Run → Edit Configurations → + → Remote JVM Debug with host localhost and port 5005, then click Debug.

Example 3 · Attaching to a running single-file program

TicketCounterDemo.javaJava
public class TicketCounterDemo {    public static void main(String[] args) throws InterruptedException {        int booked = 0;        for (int round = 1; round <= 10; round++) {            booked += 2;   // put a breakpoint here after attaching            System.out.println("Round " + round + ": booked so far " + booked);            Thread.sleep(2000);   // slow on purpose: time to attach the debugger        }        System.out.println("Counter closed");    }}
Sample output (the program runs about 20 seconds)
$ javac TicketCounterDemo.java
$ java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005 TicketCounterDemo
Listening for transport dt_socket at address: 5005
Round 1: booked so far 2
Round 2: booked so far 4
Round 3: booked so far 6
Round 4: booked so far 8
Round 5: booked so far 10
Round 6: booked so far 12
Round 7: booked so far 14
Round 8: booked so far 16
Round 9: booked so far 18
Round 10: booked so far 20
Counter closed

What this code does

  • Listening for transport dt_socket at address: 5005 is printed by the JVM, not by the program: the debug port is open. Because of suspend=n, the rounds start at once.
  • Attach the IDE to port 5005 within the 20 seconds and put a breakpoint on line 5: the next round pauses there, although the program was started from a terminal.

Example 4 · Starting shoplite-api with the debug agent

Runs in: a terminal in the shoplite-api folder

Terminal
# macOS Terminal (and Git Bash on Windows)./mvnw spring-boot:run -Dspring-boot.run.jvmArguments="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:5005"# Windows PowerShell: quote the whole -D argument.\mvnw spring-boot:run "-Dspring-boot.run.jvmArguments=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:5005"# The packaged jar, for example on a test serverjava -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:5005 -jar target/shoplite-api-1.1.0.jar
Sample output (times and process id will differ)
Listening for transport dt_socket at address: 5005
(Spring Boot banner)
2026-10-16T15:02:11.418+05:30  INFO 20516 --- [shoplite-api] [           main] com.shoplite.ShopliteApiApplication      : Starting ShopliteApiApplication using Java 21.0.7 with PID 20516
...
2026-10-16T15:02:16.903+05:30  INFO 20516 --- [shoplite-api] [           main] com.shoplite.ShopliteApiApplication      : Started ShopliteApiApplication in 5.214 seconds (process running for 5.961)

Then attach: IntelliJ "Remote JVM Debug" configuration or VS Code "attach" configuration, port 5005.

What this code does

  • spring-boot.run.jvmArguments passes the agent option to the JVM that spring-boot:run starts for the app. PowerShell needs quotes around the whole -D... argument, or it splits it at the dots.
  • The agent line comes first, then the normal startup log. From then on the app works as usual, and you can attach and detach the debugger as often as you like.

The JVM opens the port when it starts with -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=localhost:5005. server=y makes the JVM wait for a debugger to connect; suspend=n starts the program at once (suspend=y waits for the debugger before main runs); address is the port, and localhost: allows only connections from the same computer.

Predict the output

Read the debug agent

A JVM is started with the JDWP agent. Predict what happens.

Round 1 of 2

The agent has suspend=y. What happens when you start the app?

java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=localhost:5005 -jar shoplite-api.jar
// the IDE is not attached yet
JDWP has no password: whoever connects can run any code in that JVM. Use localhost:5005 on your own machine, never open the port on a public server, and never leave the agent on in production. address=*:5005 (all network interfaces) is only for a container or VM whose port you forward yourself.

Hot swap: what can change without a restart

HotSwap replaces the code of a loaded class inside a JVM that a debugger is attached to. Fix a method body, reload, and the next call runs the new code without restarting the app.

In Example 5 the categoryName bug is fixed while the app runs in debug mode. Only a method body changed, so HotSwap can apply it without a restart.

Example 5 · Fixing a method body with HotSwap

Runs in: the shoplite-api Spring Boot project, running in debug mode

Java
// src/main/java/com/shoplite/product/ProductMapper.java (part), fixed while the app runs in debug mode// Only the BODY of an existing method changed, so HotSwap can apply it without a restart.
/** The category with its parent in front; a top-level category is shown on its own. */private static String categoryName(Category category) {    Category parent = category.getParent();    return parent == null ? category.getName() : parent.getName() + " > " + category.getName();}
Sample output
IntelliJ: Build → Recompile 'ProductMapper.java' (Ctrl+Shift+F9 / Cmd+Shift+F9), then reload the changed class.
VS Code: save the file, then click Hot Code Replace on the debug toolbar (or set java.debug.settings.hotCodeReplace to "auto").

$ curl http://localhost:8080/api/v1/products/9
{"id":9,"sku":"BK-CLEAN","name":"Clean Code","categoryId":5,"categoryName":"Books","price":499.00,"stock":30,"isActive":true}

$ curl http://localhost:8080/api/v1/products/1
{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Electronics > Mobiles","price":17999.00,"stock":40,"isActive":true}

What this code does

  • The fix only changes the body of categoryName, so the reloaded class takes effect on the next request: Clean Code shows Books, and the Redmi phone shows Electronics > Mobiles.
  • If the fix had added a new helper method or a field, the reload would fail on a standard JVM and the app would need a restart (with DevTools, an automatic one).

What HotSwap can and cannot change:

  • Works: changing statements inside the body of an existing method, as in Example 5.
  • Needs a restart on a standard JVM: adding or removing methods or fields, changing a method's parameters or return type, changing a class's parent or interfaces.
  • Needs a restart in Spring Boot: anything read only at startup, such as a new @GetMapping, a new @Bean or a change in application.properties.
  • A method that is running while you reload finishes with its old code; the next call uses the new code.
Spring Boot DevTools offers a different tool: an automatic fast restart whenever classes change. It is not HotSwap, so the app starts again and your paused state is lost.

Timeouts and threads while paused

While a breakpoint holds a request thread, the rest of the world keeps its clocks running. Example 6 shows a client that gives up after 1 second while the server is paused for 1.5.

Example 6 · A client gives up while the server is paused

PausedServerDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class PausedServerDemo {    static String handleRequest() throws InterruptedException {        Thread.sleep(1500);   // stands in for 1.5 seconds paused at a breakpoint        System.out.println("Server: answer ready, but the client has already gone");        return "200 OK";    }
    public static void main(String[] args) throws Exception {        ExecutorService server = Executors.newSingleThreadExecutor();        Future<String> response = server.submit(PausedServerDemo::handleRequest);        try {            System.out.println("Client: " + response.get(1, TimeUnit.SECONDS));        } catch (TimeoutException e) {            System.out.println("Client: gave up after 1 second (read timeout)");        }        server.shutdown();        server.awaitTermination(5, TimeUnit.SECONDS);        System.out.println("Done");    }}
Output
Client: gave up after 1 second (read timeout)
Server: answer ready, but the client has already gone
Done

What this code does

  • handleRequest stands in for a request thread paused for 1.5 seconds; the client waits at most 1 second, like a browser or another service with a read timeout.
  • The server still finishes its work after the client has gone. With a real breakpoint, that is how you see a 'timeout' in the client log while your debugger shows the request completing normally.

A pause of two minutes is normal for you, but very long for the programs around it:

  • Clients time out: curl waits, but a browser page or another service usually gives up after a few seconds.
  • A paused @Transactional method keeps its database connection and row locks. Other requests for the same rows wait, then fail with MySQL's lock wait timeout (50 seconds by default).
  • ShopLite's access tokens live 15 minutes (shoplite.jwt.access-token-ttl=15m). After a long session, sign in again before the next request.
  • IntelliJ suspends all threads at a breakpoint by default; right-click the breakpoint and choose Thread to pause only the one request. VS Code lists each thread in CALL STACK, where you can pause or continue it on its own.

Next step

Check your understanding

12 quick questions