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 runs a method on another thread, so the caller continues immediately.

The mechanism is the same proxy idea behind @Transactional:

  • A proxy: @EnableAsync registers a bean post-processor that wraps every bean with @Async methods in a proxy.
  • An executor: when a caller invokes an @Async method on the proxy, the proxy does not run it. It wraps the call in a task, hands the task to a TaskExecutor, and returns at once.
  • A return value: a void method returns nothing. A method returning CompletableFuture or Future gives the caller a handle that completes when the task has run on the executor's thread.

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 types an @Async method can have
Return typeCaller getsBest for
voidNothing; errors go to an AsyncUncaughtExceptionHandlerFire-and-forget work
CompletableFuture<T>A future to combine, chain or joinResults 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 by itself: the application class still needs @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:

Java
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");
        }
    }
}
Output
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, PriceService$$SpringCGLIB$$0. The caller runs on main.
  • recordView returned at once appears before the method's own line: the call returned before the method had even started its work, which then ran on task-1.
  • All three priceFrom calls returned futures immediately, and the first was not yet done. The calls ran on task-2, task-3 and task-4, at the same time.
  • 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 @Async method, CompletableFuture.completedFuture(value) is the usual way to return a result: the proxy's own future completes with that value once the method returns. task- is the thread name prefix of Spring Boot's executor, which the next section looks at.

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:

Java
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());
        }
    }
}
Output
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 ThreadPoolTaskExecutor named applicationTaskExecutor, with 8 core threads, a maximum and a queue capacity of Integer.MAX_VALUE (2147483647), and a 60 second keep-alive. With an unbounded queue, the pool never grows past 8 threads: extra tasks wait in the queue.
  • The spring.task.execution.pool.* 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 became worker-.
  • With spring.threads.virtual.enabled=true on Java 21 or later, Spring Boot created a SimpleAsyncTaskExecutor that starts a virtual thread for each task, and the pool properties no longer apply.
  • Plain Spring Framework, with no executor bean, used a SimpleAsyncTaskExecutor that starts a new platform thread for every task, SimpleAsyncTaskExecutor-1, with no limit.
Spring Boot's spring.task.execution properties
PropertyDefaultEffect
pool.core-size8Threads kept for the pool
pool.queue-capacityUnboundedTasks waiting for a thread
pool.max-sizeUnbounded, ignored while the queue is unboundedThreads the pool grows to once the queue is full
pool.keep-alive60sIdle time before a thread is removed; core threads too, by default
thread-name-prefixtask-Thread names in logs and thread dumps
shutdown.await-terminationfalseWhether 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 when tasks could arrive faster than they finish, and decide what happens when it is full; the traps section shows the rejection.

Your own executors, and the one plain @Async uses

Separate pools keep slow report generation from delaying emails. @Async("beanName") picks an executor by name, but defining executors of your own also changes what an unqualified @Async does. This program runs the same service against four sets of executor beans:

Java
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:");
    }
}
Output
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 @Async used Spring Boot's applicationTaskExecutor.
  • Once reportExecutor existed, applicationTaskExecutor was gone: Spring Boot backs off as soon as any Executor bean is defined. Both methods then ran on report- threads, because Spring found exactly one TaskExecutor bean and used it for plain @Async too.
  • With two executor beans and no rule to choose, plain @Async silently fell back to a new SimpleAsyncTaskExecutor, a fresh unpooled thread per call. Nothing failed, but the pool sizes you configured do not apply to those calls.
  • An AsyncConfigurer bean returning mailExecutor from getAsyncExecutor() made it the default, while @Async("reportExecutor") still went to its own pool.

The rule Spring follows for plain @Async: an AsyncConfigurer first, then a single TaskExecutor bean, then a bean named taskExecutor, then a SimpleAsyncTaskExecutor. Spring Boot's own executor counts when it exists. Marking one executor @Primary also works. Spring MVC and WebFlux need a bean named applicationTaskExecutor for their own async request handling, so when you define your own executors, spring.task.execution.mode=force keeps Spring Boot's one as well.

Exceptions on the other thread

An exception thrown in an @Async method happens on a worker thread, after the caller has moved on. Where it ends up depends on the return type, so a mailer that always fails is called three ways:

Java
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());
            }
        }
    }
}
Output
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 void method's caller saw nothing at all. The exception went to the AsyncUncaughtExceptionHandler from the AsyncConfigurer, which received the method, its argument a@example.com and the exception, on task-1. Without a handler of your own, Spring's default one only logs it at ERROR level.
  • For the CompletableFuture, the exception completed the future exceptionally. exceptionally received it wrapped in a CompletionException, and the original IllegalStateException was its cause.
  • For the plain Future, get() threw ExecutionException with the original exception as its cause.

Return a CompletableFuture whenever a failure matters to the caller. For fire-and-forget methods, install a handler that records the failure where someone will see it, with enough of the arguments to retry it. An exception in a void method that only reaches a log is easy to miss.

Traps: self-invocation, lost context and a full pool

Three problems cause most @Async bugs in practice. This program shows each with Spring Boot's executor reduced to 1 thread and a queue of 1:

Java
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();
        }
    }
}
Output
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: buildAll() called this.build(), which skipped the proxy, so the "async" method ran on main and the caller waited for it. Call @Async methods from another bean.
  • Thread-bound context: the caller set a ThreadLocal tenant and an MDC request id. On task-1 the tenant was null. The request id arrived only because the TaskDecorator bean copied the MDC: Spring Boot applies a single TaskDecorator bean to its executor automatically. Security contexts, locale and transactions are thread-bound in the same way.
  • A full pool: task 1 took the only thread, task 2 took the only queue place, and task 3 was refused with TaskRejectedException, thrown to the caller. A bounded pool needs a plan for this: retry later, run in the caller with a CallerRunsPolicy, or report that the system is busy.

Transactions deserve a special warning: an @Async method does not join the caller's transaction, and may run before that transaction commits, so it can miss data the caller just wrote. @TransactionalEventListener with @Async runs the work after the commit; the @Transactional page shows the thread boundary. For general context propagation, spring.task.execution.propagate-context=true uses Micrometer's context-propagation library to copy registered thread-local values, such as tracing context, into tasks.

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:

Java
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"));
    }
}
Output
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, close() 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.
  • With await-termination=true and a 10 second period, close() took over 600 ms and all three exports finished, because the executor waited for queued tasks too.

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

Situations and what fits them
SituationUse
Fire-and-forget work such as an audit entry@Async void with an AsyncUncaughtExceptionHandler
Several slow calls in parallel, results needed@Async returning CompletableFuture, then allOf
Different kinds of work that must not block each otherOne executor bean per kind and @Async("name"), with an AsyncConfigurer for the default
Many blocking I/O tasks on Java 21+spring.threads.virtual.enabled=true, with @ConcurrencyLimit to protect downstream systems
Bursts larger than the system can absorbA bounded queue-capacity and a rejection strategy
MDC, security or tracing context in tasksA TaskDecorator bean or spring.task.execution.propagate-context
Work that must run only after a commit@TransactionalEventListener, optionally with @Async
Work that must survive a restartA message broker or a job table, not @Async
Work on a schedule@Scheduled

@Async is the simplest way to move work off the caller's thread inside one application. The scheduling page covers timed tasks, Spring Retry explains @ConcurrencyLimit and how retry combines with @Async, and Spring events shows asynchronous event listeners.