How Does Spring Boot Implement Asynchronous Programming_ This Is How Masters Do It! _ by Dylan Smith _ Javarevisited _ Medium
How Does Spring Boot Implement Asynchronous Programming_ This Is How Masters Do It! _ by Dylan Smith _ Javarevisited _ Medium
1
Search Write
Member-only story
567 10
1 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
My articles are open to everyone; non-member readers can read the full
article by clicking this link.
2 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
For example, when registering a new user, an email reminder will be sent.
Later, when you upgrade to a member, you will be given 1000 points and
other scenarios.
3 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
4 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
provided. We only need to mark this annotation on the method, and this
method can implement asynchronous calls.
@Configuration
@EnableAsync
public class AsyncConfiguration {
// do nothing
}
5 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
processing.
@Component
public class AsyncTask {
@Async
public void sendEmail() {
long t1 = System.currentTimeMillis();
Thread.sleep(2000);
long t2 = System.currentTimeMillis();
System.out.println("Sending an email took " + (t2-t1) + " ms");
}
}
@RestController
@RequestMapping("/user")
public class AsyncController {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/register")
public void register() throws InterruptedException {
long t1 = System.currentTimeMillis();
// Simulate the time required for user registration.
6 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Thread.sleep(20);
// Registration is successful. Send an email.
asyncTask.sendEmail();
long t2 = System.currentTimeMillis();
System.out.println("Registering a user took " + (t2-t1) + " ms");
}
}
As can be seen from the log, the main thread does not need to wait for the
execution of the email sending method to complete before returning,
effectively reducing the response time and improving the interface
performance.
Through the above three steps, we can easily use asynchronous methods in
Spring Boot to improve our interface performance. Isn’t it very simple?
7 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Because the above code ignores the biggest problem, which is that a custom
thread pool has not been provided for the @Async asynchronous framework.
thread pool is used. This thread pool is not a true thread pool.
Using this thread pool cannot achieve thread reuse. A new thread will be
created every time it is called. If threads are continuously created in the
system, it will eventually lead to excessive memory usage by the system and
cause an OutOfMemoryError !!!
8 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
If you output the thread name again, it can be easily found that each time the
printed thread name is in the form of [task-1], [task-2], [task-3], [task-4], and
the serial number at the back is continuously increasing.
9 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
For this reason, when using the @Async asynchronous framework in Spring,
we must customize a thread pool to replace the default
SimpleAsyncTaskExecutor .
• SimpleAsyncTaskExecutor : Not a real thread pool. This class does not reuse
threads and creates a new thread every time it is called.
10 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
11 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
@Configuration
@EnableAsync
public class SyncConfiguration {
@Bean(name = "myAsyncPoolTaskExecutor")
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
// Core thread count.
taskExecutor.setCorePoolSize(10);
// The maximum number of threads maintained in the thread pool. Only when the buffer queue
taskExecutor.setMaxPoolSize(100);
// Cache queue.
taskExecutor.setQueueCapacity(50);
// Allowed idle time. Threads other than core threads will be destroyed after the idle tim
taskExecutor.setKeepAliveSeconds(200);
// Thread name prefix for asynchronous methods.
taskExecutor.setThreadNamePrefix("async-");
/**
* When the task cache queue of the thread pool is full and the number of threads in the t
* There are usually four policies:
* ThreadPoolExecutor.AbortPolicy: Discard the task and throw RejectedExecutionException.
* ThreadPoolExecutor.DiscardPolicy: Also discard the task, but do not throw an exception.
* ThreadPoolExecutor.DiscardOldestPolicy: Discard the task at the front of the queue and
* ThreadPoolExecutor.CallerRunsPolicy: Retry adding the current task and automatically ca
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
12 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Congratulations! After customizing the thread pool, we can boldly use the
asynchronous processing capability provided by @Async . 😊
13 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
@Async("myAsyncPoolTaskExecutor")
public void sendEmail() {
long t1 = System.currentTimeMillis();
Thread.sleep(2000);
long t2 = System.currentTimeMillis();
System.out.println("Sending an email took " + (t2-t1) + " ms");
}
When there are multiple thread pools in the system, we can also configure a
default thread pool. For non-default asynchronous tasks, we can specify the
thread pool name through @Async("otherTaskExecutor") .
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfiguration implements AsyncConfigurer {
@Bean(name = "myAsyncPoolTaskExecutor")
14 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
@Bean(name = "otherTaskExecutor")
public ThreadPoolTaskExecutor otherExecutor() {
// Initialization code for thread pool configuration as above.
}
/**
* Specify the default thread pool.
*/
@Override
public Executor getAsyncExecutor() {
return executor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (ex, method, params) ->
log.error("An unknown error occurred while executing tasks in the thread pool. Exe
}
}
@Async("myAsyncPoolTaskExecutor")
15 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
@Async("otherTaskExecutor")
public void otherTask() {
//...
}
The above is all the content shared this time! If the article was helpful,
16 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Recommend reading.
Dylan Smith
Dylan Smith
17 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Responses (10)
18 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
Jay Simonini
Nov 13, 2024
This article is a very good explanation of what happens with the @Async annotation.
9 Reply
Gowtham Periyasamy
Sep 22, 2024
Thank you .
8 Reply
Ulug'bek Ro'zimboyev
Sep 16, 2024
Thanks Dylan, I find out that I used to Async incorrectly. This article was very helpful for me
12 1 reply Reply
19 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
20 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
21 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
10 Java Tricks That Will Make You a 12 Amazing IntelliJ IDEA Features
Coding Rockstar You Never Knew Existed
My articles are open to everyone; non- Amazing Intellij IDEA features for maximum
member readers can read the full article by… productivity and convenient coding…
Lists
22 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
23 of 24 2/12/25, 9:08 PM
How Does Spring Boot Implement Asynchronous Programming? This Is How Masters Do It! |... https://medium.com/javarevisited/how-does-spring-boot-implement-asynchronous-programmi...
How to avoid DTOs in Spring JPA I Will Reject Your Pull Request If
In the world of Spring Boot development, we You Violate These Design…
often find ourselves caught in the tedious… 4 Principles for Clean Code That Won’t Get
Your PR Rejected
Help Status About Careers Press Blog Privacy Terms Text to speech Teams
24 of 24 2/12/25, 9:08 PM