0% found this document useful (0 votes)
2 views35 pages

Threading in Spring Boot

Uploaded by

mohan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views35 pages

Threading in Spring Boot

Uploaded by

mohan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5/13/26, 11:52 AM Threading in Spring Boot

how to implement threads in spring boot. give me


completer tutorial with examp;es

Threading in Spring Boot — Complete Tutorial


Threads are used to run tasks parallelly in the background so your application becomes
faster and more responsive.

In Spring Boot, threading is mainly used for:

Sending emails
File processing
Excel import/export
OCR/document scanning
Background jobs
API calls
Long-running database operations

1. What is a Thread?
A thread is a small unit of execution inside a program.

Normally Spring Boot runs requests one by one.

Example:

User Request → Controller → Service → DB → Response

If one operation takes 20 seconds, the user waits.

With threads:

Main Request → Start Background Thread


→ Return Response Immediately

2. Types of Threading in Spring Boot

[Link] 1/35
5/13/26, 11:52 AM Threading in Spring Boot

Method Best For Recommended

new Thread() Basic Java ❌

Runnable Small tasks ❌

ExecutorService Thread pools ✅

@Async Spring Boot async tasks ✅✅

CompletableFuture Advanced async ✅✅

Scheduler Threads Repeated jobs ✅

3. Simple Java Thread Example


Before Spring Boot, understand core Java.

Method 1 — Extending Thread

class MyThread extends Thread {

@Override
public void run() {

for(int i=1; i<=5; i++) {


[Link]("Thread Running : " + i);

try {
[Link](1000);
} catch(Exception e) {
[Link]();
}
}
}
}

public class Test {

public static void main(String[] args) {

MyThread t1 = new MyThread();

[Link] 2/35
5/13/26, 11:52 AM Threading in Spring Boot

Java [Link]();

[Link]("Main Thread");
}
}

4. Runnable Interface Example


Better than extending Thread.

class MyTask implements Runnable {

@Override
public void run() {

for(int i=1; i<=5; i++) {


[Link]("Task Running : " + i);
}
}
}

public class Test {

public static void main(String[] args) {

Thread thread = new Thread(new MyTask());

Java [Link]();
}
}

5. Why Direct Threads Are Bad in Spring Boot


This is NOT recommended:

new Thread(() -> {


// task
Java
}).start();

Problems:

[Link] 3/35
5/13/26, 11:52 AM Threading in Spring Boot

No thread management
Memory issues
Hard to scale
Too many threads crash server

So Spring Boot uses:

Thread Pool

6. Thread Pool Concept


Instead of creating unlimited threads:

Task → Thread Pool → Reusable Threads

Benefits:
Faster
Controlled
Production ready
Better CPU usage

7. Spring Boot Async Threading ( @Async ) — MOST


IMPORTANT
This is the easiest and best approach.

Step 1 — Enable Async


Main Class

@SpringBootApplication
@EnableAsync
public class DemoApplication {

public static void main(String[] args) {


[Link]([Link], args);
Java
}
}

[Link] 4/35
5/13/26, 11:52 AM Threading in Spring Boot

Step 2 — Create Async Service

@Service
public class EmailService {

@Async
public void sendEmail() {

[Link]("Email sending started");

try {
[Link](5000);
} catch(Exception e) {
[Link]();
}

[Link]("Email sent");

Java [Link]([Link]().getName());
}
}

Step 3 — Call Service

@RestController
public class TestController {

@Autowired
private EmailService emailService;

@GetMapping("/send")
public String sendMail() {

[Link]();

return "Request Accepted";


Java
}
}

[Link] 5/35
5/13/26, 11:52 AM Threading in Spring Boot

Output
Immediately returns:

Request Accepted

Meanwhile background thread runs:

Email sending started


Email sent
task-1

8. Returning Value from Async Method


Use CompletableFuture .

Service

@Service
public class UserService {

@Async
public CompletableFuture<String> processUser() {

try {
[Link](4000);
} catch(Exception e) {
[Link]();
}

return [Link]("User Processed");


Java
}
}

Controller

@RestController
public class UserController {

[Link] 6/35
5/13/26, 11:52 AM Threading in Spring Boot

@Autowired
private UserService userService;

@GetMapping("/user")
public CompletableFuture<String> getUser() {

return [Link]();
Java
}
}

9. Custom Thread Pool Configuration


VERY IMPORTANT for production.

Config Class

@Configuration
@EnableAsync
public class AsyncConfig {

@Bean(name = "taskExecutor")
public Executor taskExecutor() {

ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor();

[Link](5);

[Link](10);

[Link](100);

[Link]("MyThread-");

[Link]();

Java
return executor;
}
}

Explanation
[Link] 7/35
5/13/26, 11:52 AM Threading in Spring Boot

Property Meaning

corePoolSize Minimum threads

maxPoolSize Maximum threads

queueCapacity Waiting tasks

threadNamePrefix Thread name

Use Custom Executor

@Async("taskExecutor")
public void process() {

Java
}

10. Real-Time Example — Excel Upload Processing


You mentioned Excel + Oracle projects before, so this is practical.

Without threads:

Upload Excel → Wait 2 minutes

With threads:

Upload Excel → Return "Processing Started"

Background thread imports data.

Service

@Service
public class ExcelService {

[Link] 8/35
5/13/26, 11:52 AM Threading in Spring Boot

@Async("taskExecutor")
public void processExcel(MultipartFile file) {

[Link]("Started Processing");

// Read Excel
// Validate Data
// Save into Oracle

Java [Link]("Completed");
}
}

Controller

@PostMapping("/upload")
public ResponseEntity<String> upload(
@RequestParam("file") MultipartFile file) {

[Link](file);

Java
return [Link]("Excel Processing Started");
}

11. Scheduled Threads


Run tasks automatically.

Enable Scheduler

@EnableScheduling
@SpringBootApplication
public class DemoApplication {

Java
}

Scheduler Example
[Link] 9/35
5/13/26, 11:52 AM Threading in Spring Boot

@Component
public class MyScheduler {

@Scheduled(fixedRate = 5000)
public void test() {

[Link]("Running Every 5 Seconds");

[Link]([Link]().getName());
Java
}
}

ChatGPT Free offer

12. Fixed Rate vs Fixed Delay


Type Meaning

fixedRate Starts every X sec

fixedDelay Waits after completion

cron Specific time

Cron Example
Every day at 10 AM:

Java
@Scheduled(cron = "0 0 10 * * ?")

13. ExecutorService Example


More control than @Async .

Example

[Link] 10/35
5/13/26, 11:52 AM Threading in Spring Boot

ExecutorService executor =
[Link](5);

[Link](() -> {

[Link]("Running Task");
Java
});

Shutdown Executor

Java
[Link]();

14. Parallel Processing Example

Java

List<Integer> list =
[Link](1,2,3,4,5);

[Link]().forEach(num -> {

[Link](num +
" " + [Link]().getName());

});

15. Common Interview Questions

Q1. Difference between process and thread?


Process Thread

Independent Lightweight

[Link] 11/35
5/13/26, 11:52 AM Threading in Spring Boot

Process Thread

Own memory Shared memory

Heavy Fast

Q2. Why use thread pool?


Reuse threads
Better performance
Avoid memory crash

Q3. Difference between Runnable and Callable?


Runnable Callable

No return Returns value

No checked exception Supports exception

16. Important Threading Problems

Race Condition
Two threads changing same data.

Example:

Java

count++;

Multiple threads can corrupt value.

Solution — synchronized

[Link] 12/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

public synchronized void increment() {


count++;
}

17. Thread Safety in Spring Boot


Spring beans are singleton by default.

Avoid:

Java

private int count = 0;

Because many users access same bean.

Use:

Local variables
AtomicInteger
synchronized
Concurrent collections

18. AtomicInteger Example

Java

AtomicInteger counter =
new AtomicInteger(0);

[Link]();

19. CompletableFuture Advanced Example


Run multiple APIs together.

Service
[Link] 13/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

@Async
public CompletableFuture<String> api1() {

return [Link]("API1");
}

@Async
public CompletableFuture<String> api2() {

return [Link]("API2");
}

Controller

Java

@GetMapping("/test")
public String test() throws Exception {

CompletableFuture<String> a = service.api1();

CompletableFuture<String> b = service.api2();

[Link](a,b).join();

return [Link]() + " " + [Link]();


}

20. Best Practices


✅ Use @Async
✅ Use thread pool
✅ Configure executor
✅ Handle exceptions
✅ Avoid shared variables
✅ Shutdown executors
✅ Use CompletableFuture for async response

21. Exception Handling in Async


[Link] 14/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

@Async
public void test() {

try {

} catch(Exception e) {

}
}

Or configure:

Java

AsyncUncaughtExceptionHandler

22. Complete Project Structure

src/main/java
|
├── controller
│ └── [Link]
|
├── service
│ └── [Link]
|
├── config
│ └── [Link]
|
└── [Link]

23. When Should You Use Threads?


Use threads for:

✅ Excel processing
✅ OCR scanning
✅ Email sending
✅ PDF generation
✅ File upload

[Link] 15/35
5/13/26, 11:52 AM Threading in Spring Boot

✅ API integrations
✅ Large DB operations

Do NOT use for:

❌ Small operations
❌ Simple CRUD
❌ Everything blindly

24. Most Important Production Advice


Never create unlimited threads:

❌ BAD

Java

for(int i=0; i<100000; i++) {


new Thread().start();
}

✅ GOOD

Java

ThreadPoolTaskExecutor

25. Recommended Learning Order


1. Core Java Threads
2. Runnable/Callable
3. ExecutorService
4. Thread Pool
5. Spring @Async
6. CompletableFuture
7. Scheduled Tasks
8. Multithreading Problems
9. Concurrent Collections

26. Final Real Production Example Flow


[Link] 16/35
5/13/26, 11:52 AM Threading in Spring Boot

Angular Upload Excel



Spring Boot API

Return "Processing Started"

Background Thread

Read Excel

Validate Data

Insert into Oracle

Update Status Table

This is exactly how enterprise applications work.

Sources

give me a detailed implementation with an example

Complete Spring Boot Threading Implementation


Example Project: Background Excel Processing System
This example shows a REAL enterprise-style implementation.

Scenario:

Angular Uploads Excel



Spring Boot API

Returns Response Immediately

Background Thread Starts

Excel Processing Happens

Data Saved into Oracle/MySQL

This is the most common threading implementation in companies.

[Link] 17/35
5/13/26, 11:52 AM Threading in Spring Boot

1. Create Spring Boot Project


Dependencies:
Spring Web
Spring Boot DevTools
Lombok
Spring Data JPA
Oracle Driver / MySQL Driver

2. Project Structure

src/main/java/com/example/demo
|
├── config
│ └── [Link]
|
├── controller
│ └── [Link]
|
├── service
│ └── [Link]
|
├── entity
│ └── [Link]
|
├── repository
│ └── [Link]
|
└── [Link]

3. Enable Async Threading


[Link]

Java

package [Link];

import [Link];
import [Link];
import [Link];

@SpringBootApplication
@EnableAsync
[Link] 18/35
5/13/26, 11:52 AM Threading in Spring Boot

public class DemoApplication {

public static void main(String[] args) {

[Link]([Link], args);
}
}

4. Create Thread Pool Configuration


[Link]

Java

package [Link];

import [Link];
import [Link];
import [Link];

import [Link];

@Configuration
public class AsyncConfig {

@Bean(name = "excelExecutor")
public Executor excelExecutor() {

ThreadPoolTaskExecutor executor =
new ThreadPoolTaskExecutor();

// Minimum threads always alive


[Link](5);

// Maximum threads
[Link](10);

// Waiting queue
[Link](100);

// Thread naming
[Link]("Excel-Thread-");

[Link]();

return executor;
}
}

[Link] 19/35
5/13/26, 11:52 AM Threading in Spring Boot

5. Create Entity
[Link]

Java

package [Link];

import [Link].*;

@Entity
@Table(name = "employee")
public class Employee {

@Id
@GeneratedValue(strategy = [Link])
private Long id;

private String empName;

private String department;

private Double salary;

public Employee() {
}

public Employee(String empName,


String department,
Double salary) {

[Link] = empName;
[Link] = department;
[Link] = salary;
}

public Long getId() {


return id;
}

public String getEmpName() {


return empName;
}

public void setEmpName(String empName) {


[Link] = empName;
}

public String getDepartment() {


return department;
[Link] 20/35
5/13/26, 11:52 AM Threading in Spring Boot

public void setDepartment(String department) {


[Link] = department;
}

public Double getSalary() {


return salary;
}

public void setSalary(Double salary) {


[Link] = salary;
}
}

6. Create Repository
[Link]

Java

package [Link];

import [Link];
import [Link];

public interface EmployeeRepository


extends JpaRepository<Employee, Long> {
}

7. Create Async Service


[Link]

Java

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

[Link] 21/35
5/13/26, 11:52 AM Threading in Spring Boot

@Service
public class ExcelService {

@Autowired
private EmployeeRepository employeeRepository;

@Async("excelExecutor")
public void processExcel(MultipartFile file) {

try {

[Link](
"Thread Name : "
+ [Link]().getName());

[Link]("Excel Processing Started");

// Simulating long processing


[Link](10000);

// Dummy data insertion


Employee emp1 =
new Employee(
"Ravi",
"IT",
45000.0
);

Employee emp2 =
new Employee(
"Rahul",
"HR",
55000.0
);

[Link](emp1);
[Link](emp2);

[Link](
"Data Saved Successfully");

[Link](
"Excel Processing Completed");

} catch (Exception e) {

[Link]();
}
}
}

[Link] 22/35
5/13/26, 11:52 AM Threading in Spring Boot

8. Create Controller
[Link]

Java

package [Link];

import [Link];
import [Link];
import [Link];
import [Link].*;
import [Link];

@RestController
@RequestMapping("/excel")
public class ExcelController {

@Autowired
private ExcelService excelService;

@PostMapping("/upload")
public ResponseEntity<String> uploadExcel(
@RequestParam("file")
MultipartFile file) {

[Link](file);

return [Link](
"Excel Processing Started in Background");
}
}

9. [Link]
MySQL Example

properties

[Link]=jdbc:mysql://localhost:3306/testdb

[Link]=root

[Link]=root

[Link]-auto=update

[Link] 23/35
5/13/26, 11:52 AM Threading in Spring Boot

[Link]-sql=true

10. Run Application


Run:

Bash

mvn spring-boot:run

11. Test API


Using Postman:

http

POST
[Link]

Body:

form-data

Key:

file

Type:

File

12. Output Flow


Immediately user gets:

Excel Processing Started in Background

Meanwhile console:

[Link] 24/35
5/13/26, 11:52 AM Threading in Spring Boot

Thread Name : Excel-Thread-1

Excel Processing Started

Data Saved Successfully

Excel Processing Completed

13. What Happened Internally?

Without Thread

Controller

Process Excel

Save DB

Return Response

User waits 10–20 sec.

With Thread

Controller

Start Background Thread

Return Response Immediately

BACKGROUND:
Process Excel
Save DB

14. Real Enterprise Flow


Production systems use:

[Link] 25/35
5/13/26, 11:52 AM Threading in Spring Boot

Upload Excel

Store file temporarily

Thread starts

Read rows

Validate rows

Batch insert

Update status table

Send notification

15. Advanced Version with CompletableFuture


Sometimes frontend waits for result.

Service

Java

@Async("excelExecutor")
public CompletableFuture<String> processExcel() {

try {

[Link](5000);

} catch (Exception e) {

return [Link](
"Processing Completed");
}

Controller

[Link] 26/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

@GetMapping("/test")
public CompletableFuture<String> test() {

return [Link]();
}

16. Parallel Execution Example


Suppose:
Read Excel
Validate Data
Generate PDF

All can run together.

Service

Java

@Async("excelExecutor")
public CompletableFuture<String> readExcel() {

return [Link](
"Excel Read");
}

@Async("excelExecutor")
public CompletableFuture<String> validateData() {

return [Link](
"Validated");
}

@Async("excelExecutor")
public CompletableFuture<String> generatePdf() {

return [Link](
"PDF Generated");
}

[Link] 27/35
5/13/26, 11:52 AM Threading in Spring Boot

Controller

Java

@GetMapping("/parallel")
public String parallel()
throws Exception {

CompletableFuture<String> a =
[Link]();

CompletableFuture<String> b =
[Link]();

CompletableFuture<String> c =
[Link]();

[Link](a,b,c).join();

return [Link]()
+ " "
+ [Link]()
+ " "
+ [Link]();
}

17. Thread Pool Deep Understanding


Suppose:

Java

corePoolSize = 5
maxPoolSize = 10
queueCapacity = 100

Case 1
5 requests come:

5 threads created

[Link] 28/35
5/13/26, 11:52 AM Threading in Spring Boot

Case 2
More requests come:

Tasks go into queue

Case 3
Queue full:

New threads created until 10

Case 4
After 10 threads:

New requests rejected

18. Exception Handling

Problem
Exception inside async method may not show properly.

Better Approach

Java

@Async("excelExecutor")
public CompletableFuture<String> process() {

try {

int x = 10 / 0;

} catch(Exception e) {

[Link] 29/35
5/13/26, 11:52 AM Threading in Spring Boot

return [Link](
"Error : " + [Link]());
}

return [Link](
"Success");
}

19. Important Production Best Practices

NEVER DO THIS

Java

for(int i=0; i<100000; i++) {

new Thread(() -> {

}).start();
}

Why bad?
Memory crash
CPU overload
Server dead

ALWAYS USE

Java

ThreadPoolTaskExecutor

20. Real Use Cases

Email Sending

[Link] 30/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

@Async
public void sendMail() {

OCR Processing

Java

@Async
public void processDocument() {

Video Processing

Java

@Async
public void convertVideo() {

Large Database Insert

Java

@Async
public void batchInsert() {

Report Generation

Java

[Link] 31/35
5/13/26, 11:52 AM Threading in Spring Boot

@Async
public void generateReport() {

21. Common Mistakes

Mistake 1
Calling async method inside same class.

❌ WRONG

Java

[Link]();

Why?

Spring proxy bypass happens.

Correct
Call from another bean.

Mistake 2
Using shared variables.

❌ BAD

Java

private int count = 0;

Multiple threads corrupt data.

Better
[Link] 32/35
5/13/26, 11:52 AM Threading in Spring Boot

Java

AtomicInteger count =
new AtomicInteger(0);

22. Debugging Threads


Print current thread:

Java

[Link](
[Link]().getName());

Output:

Excel-Thread-1

23. Async vs Scheduler


Async Scheduler

Manual trigger Automatic trigger

User action Time-based

Background processing Repeated processing

Scheduler Example

Java

@Scheduled(fixedRate = 5000)
public void runTask() {

[Link]("Running...");
}

[Link] 33/35
5/13/26, 11:52 AM Threading in Spring Boot

24. Enterprise Architecture Example

Angular Frontend

Spring Boot Controller

Async Service

Thread Pool

Oracle DB

Status Table

Notification Service

25. Best Learning Path


Learn in this order:
1. Java Threads
2. Runnable
3. Callable
4. ExecutorService
5. Thread Pool
6. Spring Async
7. CompletableFuture
8. Scheduler
9. Parallel Streams
10. Kafka/RabbitMQ async systems

26. Final Recommendation for Your Projects


Since you are working on:
Excel Upload
Oracle Database
OCR
Angular + Spring Boot

You should use:

[Link] 34/35
5/13/26, 11:52 AM Threading in Spring Boot

✅ @Async
✅ ThreadPoolTaskExecutor
✅ CompletableFuture
✅ Batch DB Inserts
✅ Scheduler for status updates

This is the same architecture used in enterprise applications.

Sources

[Link] 35/35

You might also like