Spring Boot
Multithreading
Java
Application Development
Concurrency

Start thread at springboot application

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Starting threads directly in Spring Boot is possible, but unmanaged raw threads often cause lifecycle and shutdown issues. The preferred approach is to use Spring-managed executors and application lifecycle hooks (ApplicationRunner, @EventListener(ApplicationReadyEvent.class)) so tasks start at the right time and stop gracefully.

A good design distinguishes short background jobs from long-running workers and assigns each to managed task infrastructure.

Core Sections

1. Start background work when app is ready

java
1@Component
2public class StartupRunner implements ApplicationRunner {
3
4    private final TaskExecutor taskExecutor;
5
6    public StartupRunner(TaskExecutor taskExecutor) {
7        this.taskExecutor = taskExecutor;
8    }
9
10    @Override
11    public void run(ApplicationArguments args) {
12        taskExecutor.execute(() -> {
13            // background startup work
14            System.out.println("Worker started");
15        });
16    }
17}

This avoids thread start before Spring context initialization completes.

2. Configure executor bean

java
1@Configuration
2public class AsyncConfig {
3    @Bean
4    public TaskExecutor taskExecutor() {
5        ThreadPoolTaskExecutor exec = new ThreadPoolTaskExecutor();
6        exec.setCorePoolSize(4);
7        exec.setMaxPoolSize(8);
8        exec.setQueueCapacity(100);
9        exec.setThreadNamePrefix("app-worker-");
10        exec.initialize();
11        return exec;
12    }
13}

Thread pools are safer than unmanaged new Thread(...) patterns.

3. Use @Async for method-level async tasks

java
1@EnableAsync
2@Service
3public class JobService {
4    @Async
5    public void runAsyncJob() {
6        // async work
7    }
8}

Keep async methods in separate beans to ensure proxy invocation.

4. Graceful shutdown

Long-running workers should respond to interruption and stop on application shutdown hooks.

5. Observability and control

Expose metrics for queue depth, active threads, and rejected tasks. This is essential for diagnosing overload.

Common Pitfalls

  • Creating raw threads directly and bypassing Spring lifecycle management.
  • Starting background logic before application context is fully ready.
  • Forgetting to configure executor pool sizes for workload characteristics.
  • Using @Async on self-invoked methods and expecting asynchronous behavior.
  • Ignoring shutdown signals and leaking background workers on redeploy.

Summary

In Spring Boot, start threads via managed executors and lifecycle hooks rather than raw thread creation. Use ApplicationRunner or ready-event listeners for startup tasks, configure pool sizing explicitly, and design for graceful shutdown. With proper management and observability, background concurrency stays reliable in production.

A practical way to make this guidance durable is to turn it into an executable runbook instead of leaving it as passive documentation. The runbook should include exact prerequisites, supported versions, required environment variables, and a short verification checklist. Each step should have expected output and one known failure signature so engineers can quickly classify whether they are on the happy path or hitting a known edge case. This structure is especially valuable in parallel team environments where context switches are frequent and not everyone has the same historical knowledge of the system.

It is also useful to keep a minimal reproducible fixture in source control. That fixture can be a small script, test input, sample request, or tiny deployment manifest that demonstrates both success and controlled failure behavior. When dependencies or infrastructure change, this fixture gives a fast signal about compatibility drift. Instead of debugging deep in production workflows, teams can run a focused check in minutes and identify if the regression came from tooling updates, configuration changes, or logic modifications. Reproducible fixtures also improve onboarding by showing the shortest end-to-end path.

For long-term quality, add one lightweight CI guardrail for the most failure-prone step in the workflow. Examples include schema linting, startup smoke checks, deterministic unit tests, API contract assertions, and compatibility probes for key dependencies. Keep guardrails fast and specific so failures are actionable and developers can fix issues without searching logs for long periods. If a class of issue repeats more than once, promote the corresponding manual troubleshooting step into automation. Over time, this shifts effort from reactive firefighting to preventive engineering and keeps the article aligned with real operating conditions.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.