Spring @Async: running work on other threads
@Async moves a method call onto another thread through a proxy and an executor. This page runs it with Spring Boot's default executor, custom pools and virtual threads, and shows what happens to exceptions, thread-bound context, a full queue and tasks still running at shutdown.
Contents
How @Async works
Some work does not need to finish before a method returns: sending a confirmation email, writing an audit record, or calling three suppliers at once and waiting only for the slowest. @Async
The mechanism is the same proxy idea behind @Transactional
- A proxy:
registers a bean post-processor that wraps every bean with@EnableAsync methods in a proxy.@Async - An executor: when a caller invokes an
method on the proxy, the proxy does not run it. It wraps the call in a task, hands the task to a@Async , and returns at once.TaskExecutor - A return value: a
method returns nothing. A method returningvoid orCompletableFuture gives the caller a handle that completes when the task has run on the executor's thread.Future
Three questions decide whether async code works as intended: which executor runs the task, what happens to an exception thrown on that other thread, and what the caller's thread knew that the worker thread does not. The sections below run each one.
| Return type | Caller gets | Best for |
|---|---|---|
void | Nothing; errors go to an AsyncUncaughtExceptionHandler | Fire-and-forget work |
CompletableFuture<T> | A future to combine, chain or join | Results the caller needs, parallel calls |
Future<T> | A future read with blocking get() | Older code |
The programs on this page run Spring Boot 4.1.2 without a web server, except one that runs plain Spring Framework 7.0 for comparison. Spring Boot does not switch on @Async@EnableAsync
A first @Async method
A price service records a page view, which nobody waits for, and asks three suppliers for a price, which the caller needs. Each supplier call sleeps 300 ms to stand in for a slow remote call:
package async.basics;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class AsyncBasics {
@Service
static class PriceService {
@Async
public void recordView(String sku) throws InterruptedException {
Thread.sleep(50);
System.out.println(" recordView(" + sku + ") on " + Thread.currentThread().getName());
}
@Async
public CompletableFuture<String> priceFrom(String supplier) throws InterruptedException {
Thread.sleep(300);
int price = 1000 + supplier.length() * 7;
return CompletableFuture.completedFuture(supplier + " " + price + " on "
+ Thread.currentThread().getName());
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(AsyncBasics.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run(args)) {
PriceService service = context.getBean(PriceService.class);
System.out.println("bean class: " + service.getClass().getSimpleName());
System.out.println("caller thread: " + Thread.currentThread().getName());
service.recordView("BOOK-7");
System.out.println("recordView returned at once");
Thread.sleep(200);
long start = System.nanoTime();
CompletableFuture<String> a = service.priceFrom("acme");
CompletableFuture<String> b = service.priceFrom("globex");
CompletableFuture<String> c = service.priceFrom("initech");
System.out.println("three calls returned futures, done yet: " + a.isDone());
CompletableFuture.allOf(a, b, c).join();
long millis = (System.nanoTime() - start) / 1000000;
System.out.println(" " + a.join() + "\n " + b.join() + "\n " + c.join());
System.out.println("three 300 ms calls took "
+ (millis < 600 ? "under 600 ms" : millis + " ms") + " in total");
}
}
}
bean class: AsyncBasics$PriceService$$SpringCGLIB$$0
caller thread: main
recordView returned at once
recordView(BOOK-7) on task-1
three calls returned futures, done yet: false
acme 1028 on task-2
globex 1042 on task-3
initech 1049 on task-4
three 300 ms calls took under 600 ms in total
- The bean is a CGLIB proxy,
. The caller runs onPriceService$$SpringCGLIB$$0 .main appears before the method's own line: the call returned before the method had even started its work, which then ran onrecordView returned at once .task-1- All three
calls returned futures immediately, and the first was not yet done. The calls ran onpriceFrom ,task-2 andtask-3 , at the same time.task-4 - Three 300 ms calls took under 600 ms in total, instead of about 900 ms one after the other. The exact time varies with the machine.
Inside an @AsyncCompletableFuture.completedFuture(value)task-
Which executor runs the task
The executor decides how many tasks run at once and what happens when more arrive. This program prints the executor Spring Boot creates with its defaults, with pool properties, and with virtual threads, then runs the same bean in plain Spring Framework:
package async.defaults;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class ExecutorDefaults {
@Service
static class Worker {
@Async
public CompletableFuture<String> where() {
Thread t = Thread.currentThread();
return CompletableFuture.completedFuture(
(t.getName().isEmpty() ? "(no name)" : t.getName())
+ ", virtual=" + t.isVirtual());
}
}
@EnableAsync
static class PlainSpringConfig {
}
static void boot(String label, Map<String, Object> extra) {
System.out.println(label);
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
props.putAll(extra);
SpringApplication app = new SpringApplication(ExecutorDefaults.class);
app.setDefaultProperties(props);
try (var context = app.run()) {
Object executor = context.getBean("applicationTaskExecutor");
System.out.println(" applicationTaskExecutor: " + executor.getClass().getSimpleName());
if (executor instanceof ThreadPoolTaskExecutor pool) {
System.out.println(" core " + pool.getCorePoolSize() + ", max "
+ pool.getMaxPoolSize() + ", queue capacity " + pool.getQueueCapacity()
+ ", keep-alive " + pool.getKeepAliveSeconds() + " s");
}
System.out.println(" @Async ran on " + context.getBean(Worker.class).where().join());
}
}
public static void main(String[] args) {
boot("1. Spring Boot defaults:", Map.of());
boot("2. Spring Boot with properties:", Map.of(
"spring.task.execution.pool.core-size", "2",
"spring.task.execution.pool.max-size", "4",
"spring.task.execution.pool.queue-capacity", "50",
"spring.task.execution.thread-name-prefix", "worker-"));
boot("3. Spring Boot with spring.threads.virtual.enabled=true:",
Map.of("spring.threads.virtual.enabled", "true"));
System.out.println("4. Plain Spring Framework, no Spring Boot:");
try (var context = new AnnotationConfigApplicationContext(
PlainSpringConfig.class, Worker.class)) {
System.out.println(" @Async ran on " + context.getBean(Worker.class).where().join());
}
}
}
1. Spring Boot defaults:
applicationTaskExecutor: ThreadPoolTaskExecutor
core 8, max 2147483647, queue capacity 2147483647, keep-alive 60 s
@Async ran on task-1, virtual=false
2. Spring Boot with properties:
applicationTaskExecutor: ThreadPoolTaskExecutor
core 2, max 4, queue capacity 50, keep-alive 60 s
@Async ran on worker-1, virtual=false
3. Spring Boot with spring.threads.virtual.enabled=true:
applicationTaskExecutor: SimpleAsyncTaskExecutor
@Async ran on task-1, virtual=true
4. Plain Spring Framework, no Spring Boot:
@Async ran on SimpleAsyncTaskExecutor-1, virtual=false
- Spring Boot created a
namedThreadPoolTaskExecutor , with 8 core threads, a maximum and a queue capacity ofapplicationTaskExecutor (2147483647), and a 60 second keep-alive. With an unbounded queue, the pool never grows past 8 threads: extra tasks wait in the queue.Integer.MAX_VALUE - The
properties changed it to 2 core threads, at most 4, and a queue of 50. The pool only grows beyond 2 threads once those 50 queue places are full. The thread name prefix becamespring.task.execution.pool.* .worker- - With
on Java 21 or later, Spring Boot created aspring.threads.virtual.enabled=true that starts a virtual thread for each task, and the pool properties no longer apply.SimpleAsyncTaskExecutor - Plain Spring Framework, with no executor bean, used a
that starts a new platform thread for every task,SimpleAsyncTaskExecutor , with no limit.SimpleAsyncTaskExecutor-1
| Property | Default | Effect |
|---|---|---|
pool.core-size | 8 | Threads kept for the pool |
pool.queue-capacity | Unbounded | Tasks waiting for a thread |
pool.max-size | Unbounded, ignored while the queue is unbounded | Threads the pool grows to once the queue is full |
pool.keep-alive | 60s | Idle time before a thread is removed; core threads too, by default |
thread-name-prefix | task- | Thread names in logs and thread dumps |
shutdown.await-termination | false | Whether shutdown waits for queued tasks |
The unbounded default queue hides overload: under a burst, tasks pile up in memory and wait, and nothing fails. Set a queue-capacity
Your own executors, and the one plain @Async uses
Separate pools keep slow report generation from delaying emails. @Async("beanName")@Async
package async.custom;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class CustomExecutors {
static ThreadPoolTaskExecutor pool(String prefix) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setThreadNamePrefix(prefix);
return executor;
}
@Configuration
@Profile({"one", "two", "configurer"})
static class ReportPool {
@Bean
ThreadPoolTaskExecutor reportExecutor() {
return pool("report-");
}
}
@Configuration
@Profile({"two", "configurer"})
static class MailPool {
@Bean
ThreadPoolTaskExecutor mailExecutor() {
return pool("mail-");
}
}
@Configuration
@Profile("configurer")
static class DefaultChoice implements AsyncConfigurer {
private final ThreadPoolTaskExecutor mailExecutor;
DefaultChoice(ThreadPoolTaskExecutor mailExecutor) {
this.mailExecutor = mailExecutor;
}
@Override
public Executor getAsyncExecutor() {
return mailExecutor;
}
}
@Service
static class Jobs {
@Async("reportExecutor")
public CompletableFuture<String> report() {
return CompletableFuture.completedFuture(Thread.currentThread().getName());
}
@Async
public CompletableFuture<String> unqualified() {
return CompletableFuture.completedFuture(Thread.currentThread().getName());
}
}
static void run(String profile, String label) {
System.out.println(label);
SpringApplication app = new SpringApplication(CustomExecutors.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run("--spring.profiles.active=" + profile)) {
System.out.println(" executor beans: "
+ Arrays.toString(context.getBeanNamesForType(TaskExecutor.class)));
Jobs jobs = context.getBean(Jobs.class);
if (context.containsBean("reportExecutor")) {
System.out.println(" @Async(\"reportExecutor\") ran on " + jobs.report().join());
}
System.out.println(" plain @Async ran on " + jobs.unqualified().join());
}
}
public static void main(String[] args) {
run("none", "1. No executor bean of your own:");
run("one", "2. One custom executor, reportExecutor:");
run("two", "3. Two custom executors, no default chosen:");
run("configurer", "4. Two custom executors and an AsyncConfigurer:");
}
}
1. No executor bean of your own:
executor beans: [applicationTaskExecutor]
plain @Async ran on task-1
2. One custom executor, reportExecutor:
executor beans: [reportExecutor]
@Async("reportExecutor") ran on report-1
plain @Async ran on report-2
3. Two custom executors, no default chosen:
executor beans: [mailExecutor, reportExecutor]
@Async("reportExecutor") ran on report-1
plain @Async ran on SimpleAsyncTaskExecutor-1
4. Two custom executors and an AsyncConfigurer:
executor beans: [mailExecutor, reportExecutor]
@Async("reportExecutor") ran on report-1
plain @Async ran on mail-1
- With no executor bean of your own, plain
used Spring Boot's@Async .applicationTaskExecutor - Once
existed,reportExecutor was gone: Spring Boot backs off as soon as anyapplicationTaskExecutor bean is defined. Both methods then ran onExecutor threads, because Spring found exactly onereport- bean and used it for plainTaskExecutor too.@Async - With two executor beans and no rule to choose, plain
silently fell back to a new@Async , a fresh unpooled thread per call. Nothing failed, but the pool sizes you configured do not apply to those calls.SimpleAsyncTaskExecutor - An
bean returningAsyncConfigurer frommailExecutor made it the default, whilegetAsyncExecutor() still went to its own pool.@Async("reportExecutor")
The rule Spring follows for plain @AsyncAsyncConfigurerTaskExecutortaskExecutorSimpleAsyncTaskExecutor@PrimaryapplicationTaskExecutorspring.task.execution.mode=force
Exceptions on the other thread
An exception thrown in an @Async
package async.errors;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class AsyncExceptions {
static final CountDownLatch handled = new CountDownLatch(1);
static volatile String handlerReport;
@Configuration
static class ErrorHandling implements AsyncConfigurer {
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (Throwable e, Method method, Object... params) -> {
handlerReport = " handler: " + method.getName() + Arrays.toString(params)
+ " threw " + e.getMessage() + " on " + Thread.currentThread().getName();
handled.countDown();
};
}
}
@Service
static class Mailer {
@Async
public void send(String to) {
throw new IllegalStateException("SMTP refused " + to);
}
@Async
public CompletableFuture<String> sendWithReceipt(String to) {
throw new IllegalStateException("SMTP refused " + to);
}
@Async
public Future<String> legacyFuture(String to) {
throw new IllegalStateException("SMTP refused " + to);
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(AsyncExceptions.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (var context = app.run(args)) {
Mailer mailer = context.getBean(Mailer.class);
System.out.println("1. void method:");
mailer.send("a@example.com");
System.out.println(" caller saw nothing");
handled.await();
System.out.println(handlerReport);
System.out.println("2. CompletableFuture:");
String result = mailer.sendWithReceipt("b@example.com")
.exceptionally(e -> "fallback receipt (" + e.getClass().getSimpleName()
+ ": " + e.getCause().getMessage() + ")")
.join();
System.out.println(" " + result);
System.out.println("3. Future, read with get():");
try {
mailer.legacyFuture("c@example.com").get();
} catch (ExecutionException e) {
System.out.println(" ExecutionException caused by "
+ e.getCause().getClass().getSimpleName() + ": "
+ e.getCause().getMessage());
}
}
}
}
1. void method:
caller saw nothing
handler: send[a@example.com] threw SMTP refused a@example.com on task-1
2. CompletableFuture:
fallback receipt (CompletionException: SMTP refused b@example.com)
3. Future, read with get():
ExecutionException caused by IllegalStateException: SMTP refused c@example.com
- The
method's caller saw nothing at all. The exception went to thevoid from theAsyncUncaughtExceptionHandler , which received the method, its argumentAsyncConfigurer and the exception, ona@example.com . Without a handler of your own, Spring's default one only logs it attask-1 level.ERROR - For the
, the exception completed the future exceptionally.CompletableFuture received it wrapped in aexceptionally , and the originalCompletionException was its cause.IllegalStateException - For the plain
,Future threwget() with the original exception as its cause.ExecutionException
Return a CompletableFuturevoid
Traps: self-invocation, lost context and a full pool
Three problems cause most @Async
package async.traps;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.TaskDecorator;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class AsyncTraps {
/** Spring Boot applies a single TaskDecorator bean to its auto-configured executor. */
@Bean
TaskDecorator mdcCopier() {
return task -> {
Map<String, String> context = MDC.getCopyOfContextMap();
return () -> {
if (context != null) {
MDC.setContextMap(context);
}
try {
task.run();
} finally {
MDC.clear();
}
};
};
}
static final ThreadLocal<String> TENANT = new ThreadLocal<>();
@Service
static class ReportService {
static CountDownLatch release = new CountDownLatch(1);
public String buildAll() {
return "buildAll called build() on " + this.build().join();
}
@Async
public CompletableFuture<String> build() {
return CompletableFuture.completedFuture(Thread.currentThread().getName()
+ ", tenant=" + TENANT.get() + ", MDC requestId=" + MDC.get("requestId"));
}
@Async
public CompletableFuture<String> slow() throws InterruptedException {
release.await();
return CompletableFuture.completedFuture("done");
}
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(AsyncTraps.class);
app.setDefaultProperties(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.task.execution.pool.core-size", "1",
"spring.task.execution.pool.max-size", "1",
"spring.task.execution.pool.queue-capacity", "1"));
try (var context = app.run(args)) {
ReportService reports = context.getBean(ReportService.class);
System.out.println("1. Calling an @Async method on this:");
System.out.println(" " + reports.buildAll());
System.out.println("2. ThreadLocal and MDC set by the caller:");
TENANT.set("acme");
MDC.put("requestId", "r-42");
System.out.println(" caller: " + Thread.currentThread().getName()
+ ", tenant=" + TENANT.get() + ", MDC requestId=" + MDC.get("requestId"));
System.out.println(" async: " + reports.build().join());
TENANT.remove();
MDC.clear();
System.out.println("3. A full pool, 1 thread and a queue of 1:");
for (int i = 1; i <= 3; i++) {
try {
reports.slow();
System.out.println(" task " + i + " accepted");
Thread.sleep(100);
} catch (TaskRejectedException e) {
System.out.println(" task " + i + " rejected: TaskRejectedException");
}
}
ReportService.release.countDown();
}
}
}
1. Calling an @Async method on this:
buildAll called build() on main, tenant=null, MDC requestId=null
2. ThreadLocal and MDC set by the caller:
caller: main, tenant=acme, MDC requestId=r-42
async: task-1, tenant=null, MDC requestId=r-42
3. A full pool, 1 thread and a queue of 1:
task 1 accepted
task 2 accepted
task 3 rejected: TaskRejectedException
- Self-invocation:
calledbuildAll() , which skipped the proxy, so the "async" method ran onthis.build() and the caller waited for it. Callmain methods from another bean.@Async - Thread-bound context: the caller set a
tenant and an MDC request id. OnThreadLocal the tenant wastask-1 . The request id arrived only because thenull bean copied the MDC: Spring Boot applies a singleTaskDecorator bean to its executor automatically. Security contexts, locale and transactions are thread-bound in the same way.TaskDecorator - A full pool: task 1 took the only thread, task 2 took the only queue place, and task 3 was refused with
, thrown to the caller. A bounded pool needs a plan for this: retry later, run in the caller with aTaskRejectedException , or report that the system is busy.CallerRunsPolicy
Transactions deserve a special warning: an @Async@TransactionalEventListener@Asyncspring.task.execution.propagate-context=true
What happens to running tasks at shutdown
Deployments stop applications all the time, often while background work is running. Three 300 ms exports are queued on a single thread, and the context is closed as soon as the first starts:
package async.shutdown;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
@SpringBootApplication
@EnableAsync
public class AsyncShutdown {
@Service
static class ExportService {
static final List<String> outcomes = new CopyOnWriteArrayList<>();
static volatile CountDownLatch started;
@Async
public void export(int n) {
started.countDown();
try {
Thread.sleep(300);
outcomes.add("export " + n + " finished");
} catch (InterruptedException e) {
outcomes.add("export " + n + " interrupted");
}
}
}
static void run(String label, Map<String, Object> extra) throws Exception {
System.out.println(label);
ExportService.started = new CountDownLatch(1);
ExportService.outcomes.clear();
Map<String, Object> props = new HashMap<>(Map.of(
"spring.main.banner-mode", "off",
"logging.level.root", "WARN",
"spring.task.execution.pool.core-size", "1"));
props.putAll(extra);
SpringApplication app = new SpringApplication(AsyncShutdown.class);
app.setDefaultProperties(props);
var context = app.run();
ExportService exports = context.getBean(ExportService.class);
for (int n = 1; n <= 3; n++) {
exports.export(n);
}
ExportService.started.await();
long start = System.nanoTime();
context.close();
long closeMillis = (System.nanoTime() - start) / 1000000;
Thread.sleep(1500);
System.out.println(" close() took " + (closeMillis < 600 ? "under" : "over")
+ " 600 ms; outcomes: " + ExportService.outcomes);
}
public static void main(String[] args) throws Exception {
run("1. Defaults:", Map.of());
run("2. spring.task.execution.shutdown.await-termination=true:", Map.of(
"spring.task.execution.shutdown.await-termination", "true",
"spring.task.execution.shutdown.await-termination-period", "10s"));
}
}
1. Defaults:
close() took under 600 ms; outcomes: [export 1 finished, export 2 interrupted]
2. spring.task.execution.shutdown.await-termination=true:
close() took over 600 ms; outcomes: [export 1 finished, export 2 finished, export 3 finished]
- With the defaults,
waited for the running export 1, then shut the executor down. Export 2 had just started and was interrupted, and export 3 never ran. Nothing reported the lost work.close() - With
and a 10 second period,await-termination=true took over 600 ms and all three exports finished, because the executor waited for queued tasks too.close()
The waiting period should fit inside the platform's own shutdown grace period, which is 30 seconds by default in Kubernetes; after that the process is killed regardless. Work that must not be lost belongs in a durable queue or a database table, processed by a job that can resume, not only in an in-memory executor queue.
Choosing how to run work asynchronously
| Situation | Use |
|---|---|
| Fire-and-forget work such as an audit entry | @Async voidAsyncUncaughtExceptionHandler |
| Several slow calls in parallel, results needed | @AsyncCompletableFutureallOf |
| Different kinds of work that must not block each other | One executor bean per kind and @Async("name")AsyncConfigurer |
| Many blocking I/O tasks on Java 21+ | spring.threads.virtual.enabled=true@ConcurrencyLimit |
| Bursts larger than the system can absorb | A bounded queue-capacity |
| MDC, security or tracing context in tasks | A TaskDecoratorspring.task.execution.propagate-context |
| Work that must run only after a commit | @TransactionalEventListener@Async |
| Work that must survive a restart | A message broker or a job table, not @Async |
| Work on a schedule | @Scheduled |
@Async@ConcurrencyLimit@Async