Skip to content
javahacks.dev
Debugging

Slow Java Startup Debug Steps to Find the Real Cause

Find why a Java application starts slowly: measure each phase, log class loading and bean creation, catch DNS and network stalls, then fix the biggest item.

7 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Docker, Spring Security and Apache Maven logos.

A service that takes 90 seconds to start is slow to deploy, slow to scale out and slow to come back after a crash. Rollouts stretch, autoscaling lags behind the traffic that triggered it, and a readiness probe tuned for 30 seconds kills the pod before it ever answers. The fix depends entirely on where the time goes, and guessing is how teams end up adding --add-opens flags and lazy initialization to a service whose real problem was a database host that never resolved.

This post walks the investigation in the order that wastes the least time: total, JVM and class loading, framework, then a stuck main thread. Each step has a command, the output to expect and the conclusion to draw. The small lab programs ran on JDK 17.0.1 on a 10-core laptop, and the Spring parts target Spring Boot 4 on Java 25.

Measure the total and the phases

Start with a number you can compare after every change. Run the jar under time and keep the result:

Shell
time java -jar app.jar

Spring Boot prints its own total near the end of startup:

Text
Started OrdersApplication in 38.412 seconds (process running for 40.07)

Read those two numbers as different things. "Started in 38.412 seconds" is the time inside Spring's SpringApplication.run. "Process running for 40.07" starts at JVM launch, so the 1.7 second difference is the JVM booting and loading the first classes before your main begins. If that gap is large, the problem is below the framework: a slow disk, a huge fat jar being unpacked, a security manager or a tiny CPU quota.

A bare JVM is fast, and knowing the floor stops you chasing a few milliseconds. This program reports how long the JVM had been alive when main reached it, how long a hostname lookup took and how many classes were loaded:

src/main/java/dev/javahacks/boot/Boot.javajava
import java.lang.management.ManagementFactory;
import java.net.InetAddress;

public class Boot {
    public static void main(String[] args) throws Exception {
        long jvmStart = ManagementFactory.getRuntimeMXBean().getStartTime();
        long t0 = System.nanoTime();
        InetAddress.getByName("localhost");
        long dns = (System.nanoTime() - t0) / 1_000_000;
        long sinceStart = System.currentTimeMillis() - jvmStart;
        System.out.println("ms since JVM start: " + sinceStart);
        System.out.println("localhost lookup ms: " + dns);
        System.out.println("loaded classes: "
            + ManagementFactory.getClassLoadingMXBean().getTotalLoadedClassCount());
    }
}
Text
ms since JVM start: 38
localhost lookup ms: 4
loaded classes: 753

A hello-world JVM is up in about 40 ms and has loaded 753 classes, 745 of them from the JDK's own archive. A Spring Boot application loads 15,000 to 30,000. That ratio is why startup scales with your dependency count more than with your code.

Count what the class loader does

Class loading is the first place a fat classpath hurts. Log every load to a file and count it:

Shell
java -Xlog:class+load:file=classload.log -jar app.jar
wc -l classload.log
grep -c "source: jrt:/" classload.log     # classes from the JDK image
grep -c "source: file:" classload.log     # classes read from your jars

Our lab run wrote 755 lines for 753 classes. For a real service, the useful question is which jars the file-sourced classes came from, because a dependency you forgot you had shows up as thousands of lines:

Shell
grep "source: file:" classload.log \
  | sed -E 's/.*source: file:([^ ]*\.jar).*/\1/' \
  | sort | uniq -c | sort -rn | head

A jar near the top that your code never calls is a candidate for removal. The related failure mode, the wrong version of a class winning, is covered in classpath problems and class loading.

You can see the cost of the JDK's built-in sharing by turning it off. The same program took 0.093 s with -Xshare:off and 0.058 s with the default shared archive, a 35 ms difference on a program that loads 750 classes. Scale that to 25,000 classes and the shared archive stops being a detail. Application Class Data Sharing extends it to your own jars:

Shell
# 1. Training run: record the classes the app loads and write an archive on exit
java -XX:ArchiveClassesAtExit=app.jsa -jar app.jar

# 2. Production run: map the archive instead of parsing and verifying the classes
java -XX:SharedArchiveFile=app.jsa -jar app.jar

On the lab program the archive was 480 KB and the run dropped from 0.058 s to 0.052 s. The gain is small here because the program has no application classes. For a Spring service the saving grows with the number of application and library classes, so measure it on yours.

Ask Spring Boot what took the time

When the JVM and class loading are not the problem, the framework's own timeline is. Record the steps Spring performs:

src/main/java/dev/javahacks/orders/OrdersApplication.javajava
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;

@SpringBootApplication
public class OrdersApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(OrdersApplication.class);
        app.setApplicationStartup(new BufferingApplicationStartup(4096));
        app.run(args);
    }
}
src/main/resources/application.propertiesproperties
management.endpoints.web.exposure.include=startup

The buffer keeps the first 4,096 events, so a service with a very large context needs a bigger number or the timeline is silently cut off. Fetch it after startup and sort by duration:

Shell
curl -s -X POST localhost:8080/actuator/startup \
  | jq '[.timeline.events[] | {step: .startupStep.name, ms: (.duration | sub("PT";"") ), tags: [.startupStep.tags[] | select(.key=="beanName") | .value]}]
        | sort_by(.ms) | reverse | .[0:5]'

Durations come back as ISO-8601 strings such as PT2.301S, so the sort above is lexicographic and only a first approximation. For a precise ranking, pipe through a small script or use the Actuator Startup view in your metrics tool. The steps to look for are spring.beans.instantiate, which names the bean, and spring.context.refresh as the umbrella. A DataSource, a Kafka listener container or a cache warmer near the top tells you which collaborator is slow. For the wiring side of that investigation see debugging Spring bean wiring, and for why an autoconfiguration kicked in at all, the conditions report.

Take thread dumps while it is quiet

Sometimes the log goes silent for fifteen seconds and no timeline helps because the time is spent inside one call. A thread dump shows what that call is. Take three, five seconds apart:

Shell
for i in 1 2 3; do
  jcmd $(pgrep -f app.jar) Thread.print | grep -A 18 '"main"'
  sleep 5
done

Read the top frames of the main thread:

Text
"main" #1 prio=5 tid=0x00007f... nid=0x1c03 runnable
   java.lang.Thread.State: RUNNABLE
	at java.base/sun.nio.ch.SocketDispatcher.read0(Native Method)
	at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:...)

That trace is a startup blocked on a database connection. Three dumps with the same frame mean the call is the bottleneck, and three dumps with different frames mean the time is spread across many small steps, which points back to scanning and bean count. The reading technique is the same one described in using jcmd, jstack and jmap safely in production.

The usual suspects

What the dump or timeline showsCauseFix
Frame in SocketDispatcher.read0 or connect, quiet logConnecting to an unreachable database or brokerFix the route, set connect timeouts, set spring.datasource.hikari.initialization-fail-timeout
Frame in InetAddress.getByNameReverse DNS, or a hostname missing from /etc/hostsFix the resolver or add the entry
ClassPathScanningCandidateComponentProviderComponent scan over a wide package or large jarsNarrow scanBasePackages, remove unused dependencies
15 to 25 s in HibernateSchema validation or metadata build over many entitiesDo not validate against a live schema at every start
Everything slow, CPU pinned at the limitContainer CPU quota under 1 coreRaise the limit for startup, see CPU limits in containers
Slow only the first start on a nodeCold disk cache, image pullPre-pull images, use a faster volume
Many @PostConstruct methodsWarm-up work running inside bean creationMove it to an async task after readiness

The CPU row deserves its own sentence. Class loading, bytecode verification and the JIT compiler are all CPU bound, so a pod limited to 500 millicores starts a Spring Boot service several times slower than the same pod at 2 cores. Before profiling anything else, raise resources.limits.cpu for one test deploy and compare. See heap and CPU numbers in containers.

Reduce the cost once you know the cause

Apply one change per measurement, or you will not know which one worked:

  • Lazy initialization. spring.main.lazy-initialization=true defers bean creation to first use. Startup shrinks, the first request pays for it, and a misconfigured bean now fails in production at 3 a.m. instead of at deploy.
  • Application CDS. The archive above. It costs one extra step in the image build and nothing at runtime.
  • AOT cache. JDK 24 and later can store linked classes and profile data from a training run (JEP 483 and JEP 514), a step beyond plain CDS.
  • Spring AOT and native images. Moving reflection and proxy generation to build time cuts startup to well under a second at the price of a longer build and a stricter programming model. See why Quarkus starts fast.
  • Fewer dependencies. The cheapest class to load is the one that is not on the classpath.

When this guide does not fit

Slow warm-up after the application is up, where the first requests take 800 ms and the next ones take 20, is a JIT question and not a startup one, see tiered compilation. A service that fails to start rather than starting slowly belongs in application failed to start. The reference for the timeline is the Spring Boot actuator startup endpoint, and JEP 483 describes ahead-of-time class loading and linking.

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.