Threading in Spring Boot
Threading in Spring Boot
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.
Example:
With threads:
[Link] 1/35
5/13/26, 11:52 AM Threading in Spring Boot
@Override
public void run() {
try {
[Link](1000);
} catch(Exception e) {
[Link]();
}
}
}
}
[Link] 2/35
5/13/26, 11:52 AM Threading in Spring Boot
Java [Link]();
[Link]("Main Thread");
}
}
@Override
public void run() {
Java [Link]();
}
}
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
Thread Pool
Benefits:
Faster
Controlled
Production ready
Better CPU usage
@SpringBootApplication
@EnableAsync
public class DemoApplication {
[Link] 4/35
5/13/26, 11:52 AM Threading in Spring Boot
@Service
public class EmailService {
@Async
public void sendEmail() {
try {
[Link](5000);
} catch(Exception e) {
[Link]();
}
[Link]("Email sent");
Java [Link]([Link]().getName());
}
}
@RestController
public class TestController {
@Autowired
private EmailService emailService;
@GetMapping("/send")
public String sendMail() {
[Link]();
[Link] 5/35
5/13/26, 11:52 AM Threading in Spring Boot
Output
Immediately returns:
Request Accepted
Service
@Service
public class UserService {
@Async
public CompletableFuture<String> processUser() {
try {
[Link](4000);
} catch(Exception e) {
[Link]();
}
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
}
}
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
@Async("taskExecutor")
public void process() {
Java
}
Without threads:
With threads:
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");
}
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]([Link]().getName());
Java
}
}
Cron Example
Every day at 10 AM:
Java
@Scheduled(cron = "0 0 10 * * ?")
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]();
Java
List<Integer> list =
[Link](1,2,3,4,5);
[Link]().forEach(num -> {
[Link](num +
" " + [Link]().getName());
});
Independent Lightweight
[Link] 11/35
5/13/26, 11:52 AM Threading in Spring Boot
Process Thread
Heavy Fast
Race Condition
Two threads changing same data.
Example:
Java
count++;
Solution — synchronized
[Link] 12/35
5/13/26, 11:52 AM Threading in Spring Boot
Java
Avoid:
Java
Use:
Local variables
AtomicInteger
synchronized
Concurrent collections
Java
AtomicInteger counter =
new AtomicInteger(0);
[Link]();
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();
Java
@Async
public void test() {
try {
} catch(Exception e) {
}
}
Or configure:
Java
AsyncUncaughtExceptionHandler
src/main/java
|
├── controller
│ └── [Link]
|
├── service
│ └── [Link]
|
├── config
│ └── [Link]
|
└── [Link]
✅ 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
❌ Small operations
❌ Simple CRUD
❌ Everything blindly
❌ BAD
Java
✅ GOOD
Java
ThreadPoolTaskExecutor
Sources
Scenario:
[Link] 17/35
5/13/26, 11:52 AM Threading in Spring Boot
2. Project Structure
src/main/java/com/example/demo
|
├── config
│ └── [Link]
|
├── controller
│ └── [Link]
|
├── service
│ └── [Link]
|
├── entity
│ └── [Link]
|
├── repository
│ └── [Link]
|
└── [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
[Link]([Link], args);
}
}
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();
// 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;
public Employee() {
}
[Link] = empName;
[Link] = department;
[Link] = salary;
}
6. Create Repository
[Link]
Java
package [Link];
import [Link];
import [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());
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
Bash
mvn spring-boot:run
http
POST
[Link]
Body:
form-data
Key:
file
Type:
File
Meanwhile console:
[Link] 24/35
5/13/26, 11:52 AM Threading in Spring Boot
Without Thread
Controller
↓
Process Excel
↓
Save DB
↓
Return Response
With Thread
Controller
↓
Start Background Thread
↓
Return Response Immediately
BACKGROUND:
Process Excel
Save DB
[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
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]();
}
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]();
}
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:
Case 3
Queue full:
Case 4
After 10 threads:
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");
}
NEVER DO THIS
Java
}).start();
}
Why bad?
Memory crash
CPU overload
Server dead
ALWAYS USE
Java
ThreadPoolTaskExecutor
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() {
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() {
Mistake 1
Calling async method inside same class.
❌ WRONG
Java
[Link]();
Why?
Correct
Call from another bean.
Mistake 2
Using shared variables.
❌ BAD
Java
Better
[Link] 32/35
5/13/26, 11:52 AM Threading in Spring Boot
Java
AtomicInteger count =
new AtomicInteger(0);
Java
[Link](
[Link]().getName());
Output:
Excel-Thread-1
Scheduler Example
Java
@Scheduled(fixedRate = 5000)
public void runTask() {
[Link]("Running...");
}
[Link] 33/35
5/13/26, 11:52 AM Threading in Spring Boot
Angular Frontend
↓
Spring Boot Controller
↓
Async Service
↓
Thread Pool
↓
Oracle DB
↓
Status Table
↓
Notification Service
[Link] 34/35
5/13/26, 11:52 AM Threading in Spring Boot
✅ @Async
✅ ThreadPoolTaskExecutor
✅ CompletableFuture
✅ Batch DB Inserts
✅ Scheduler for status updates
Sources
[Link] 35/35