Sub topic 7
Long-running tasks with @Async
This chapter assumes you know how to declare @Scheduled methods, the difference between fixedRate and fixedDelay, and how the scheduler thread pool is sized. You should also be comfortable with Spring proxies at a basic level, and with threads and shared state.
The problem: a slow task holds a scheduler thread
A @Scheduled method runs on a scheduler thread. By default Spring Boot gives the scheduler a single thread. If one task takes 90 seconds, every other scheduled task waits behind it. You can raise spring.task.scheduling.pool.size, but a slow task still holds a scheduler thread for its whole run.
@Async moves the work to a different executor. The scheduler thread only submits the task and returns at once, so it stays free for other triggers.
Combining @Scheduled with @Async
Two steps are needed. First, enable async processing. Second, add @Async to the scheduled method.
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncConfig {
}import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class SlowJobs {
private static final Logger log = LoggerFactory.getLogger(SlowJobs.class);
@Scheduled(fixedRate = 60000)
@Async
public void slowTask() throws InterruptedException {
log.info("start on {}", Thread.currentThread().getName());
Thread.sleep(90_000);
log.info("end");
}
}The log line shows a thread name such as task-1, not scheduling-1. That confirms the body runs on the async executor.
What changes: the scheduler no longer waits
Without @Async, fixedRate and fixedDelay tasks never overlap with themselves. The scheduler waits for a run to finish before it considers the next one. With @Async, that guarantee disappears, because the scheduler only sees the quick hand-off.
Consider the example above. It fires every 60 seconds but takes 90 seconds. At t=60 s a second run starts while the first is still going. Without a limit, runs pile up.
| Setup | Scheduler thread blocked? | Can a task overlap itself? |
|---|---|---|
| `@Scheduled` only, `fixedDelay` | Yes, for the whole run | No |
| `@Scheduled` only, `fixedRate` | Yes, for the whole run | No. A late run starts as soon as the previous one ends |
| `@Scheduled` + `@Async` | No, only for the hand-off | Yes, unless you prevent it |
Note that fixedDelay with @Async is the most misleading combination. The delay is measured from the end of the hand-off, not from the end of the real work. It then behaves almost like a fixed rate equal to the delay.
The default async executor
If you do not name an executor, @Async uses the one Spring Boot auto-configures. It is a ThreadPoolTaskExecutor with these defaults:
- core size 8
- an unbounded queue
- thread name prefix
task-
You tune it under spring.task.execution:
spring:
task:
execution:
thread-name-prefix: async-
pool:
core-size: 4
max-size: 8
queue-capacity: 50
shutdown:
await-termination: true
await-termination-period: 30sBecause the default queue is unbounded, max-size has no effect until you set a finite queue-capacity. A pool only grows beyond its core size after the queue is full. With an unbounded queue, a slow task that is triggered too often will just fill the queue and use memory.
Three ways to stop runs from overlapping
1. A guard flag inside the task
The simplest approach is to skip a run when the previous one is still active.
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ExportJob {
private static final Logger log = LoggerFactory.getLogger(ExportJob.class);
private final AtomicBoolean running = new AtomicBoolean(false);
@Scheduled(fixedRate = 60000)
@Async
public void export() {
if (!running.compareAndSet(false, true)) {
log.warn("previous export still running, skipping this trigger");
return;
}
try {
// long-running work
} finally {
running.set(false);
}
}
}The finally block matters. If the work throws and you forget to reset the flag, the job never runs again.
2. A dedicated single-thread executor
You can give the job its own executor that holds one thread and refuses extra work. A pool with one thread and no queue rejects a submission while the thread is busy. A DiscardPolicy then drops it quietly.
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
public class ExecutorConfig {
@Bean("reportExecutor")
public ThreadPoolTaskExecutor reportExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(1);
executor.setMaxPoolSize(1);
executor.setQueueCapacity(0);
executor.setThreadNamePrefix("report-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
return executor;
}
}@Scheduled(fixedRate = 60000)
@Async("reportExecutor")
public void buildReport() {
// runs on report-1, never twice at once
}This isolates the job. It cannot starve other @Async work, and other work cannot starve it. The cost is silent dropping, so log it if you need to know. A ThreadPoolExecutor.AbortPolicy, which is the default, throws a TaskRejectedException that you would see on the scheduler thread.
3. Do not use @Async at all
If the real problem is that one slow task blocks the others, a larger scheduler pool may be enough. With spring.task.scheduling.pool.size: 4, four tasks can run concurrently, and each task still never overlaps with itself. This keeps the simple no-overlap behavior and costs nothing in complexity. Use @Async when you need a separate executor with its own limits, or when you want to decouple the work from the trigger deliberately.
Pitfalls of @Async on scheduled methods
- It works through a proxy.
@Asynconly applies when the call goes through the Spring proxy. The scheduler calls the bean from outside, so that is fine. But if another method in the same class calls an@Asyncmethod directly, it runs synchronously. - Return types are limited. An
@Asyncmethod may returnvoid,FutureorCompletableFuture. The scheduler ignores the return value of a@Scheduledmethod, so usevoid. - Exceptions go elsewhere. The scheduler's error handler never sees an exception thrown by an
@Async voidmethod, because the scheduler thread has already moved on. Spring routes it to anAsyncUncaughtExceptionHandler, which by default only logs it at ERROR level. Wrap the body in your own try/catch if you need to count failures or alert. The next chapter covers error handling in more detail. - The method cannot be
private,finalorstatic. The proxy has to override it. - Context is lost.
ThreadLocalvalues, such as security context or MDC logging fields, do not travel to the executor thread unless you configure a task decorator.
Choosing between the options
| Situation | Suggested approach |
|---|---|
| Several short tasks, one occasionally slow | Increase `spring.task.scheduling.pool.size` |
| One heavy task that must not starve others | `@Async` with a dedicated executor |
| Task must never overlap with itself | Keep it synchronous, or add a guard or a single-thread executor |
| Task may overlap and is safe to run in parallel | `@Async` with a bounded queue |
Exercise
A method is annotated with @Scheduled(fixedDelay = 10000) and @Async. The body takes 60 seconds. How often does it start, and why? What would you change so that at most one run is active?
Show answer
It starts roughly every 10 seconds, so up to six runs can be active at once. With @Async the scheduler thread returns right after handing the work off, so the 10-second delay is measured from that hand-off and not from the end of the real work. To allow only one run, remove @Async (and raise the scheduler pool size if other tasks need to run), or use a guard such as an AtomicBoolean, or a dedicated executor with one thread and no queue.
Exercise
You set spring.task.execution.pool.core-size=2 and max-size=10 but leave queue-capacity unset. Under heavy load, how many threads does the pool use, and why?
Show answer
Two. The default queue is unbounded, so the pool never sees a full queue, and a pool only grows past its core size when the queue is full. Extra tasks wait in the queue and max-size is never reached. Set a finite queue-capacity to make the pool grow.