Sub topic 7
Long-running tasks with @Async
This chapter assumes you can write @Scheduled methods and know that Spring Boot's scheduler runs on a small thread pool, as covered in the previous chapter. It also assumes basic familiarity with threads and concurrency.
The problem: a slow task holds the scheduler thread
By default, Spring Boot's scheduler has a single thread. If one scheduled method takes 90 seconds, every other scheduled method waits until it finishes. A task meant to run every 10 seconds then runs late.
You can raise spring.task.scheduling.pool.size. That helps, but a slow task still occupies a scheduler thread for its whole run. Scheduler threads are meant for triggering work, so there is a second option: hand the work to a different executor.
Handing work off with @Async
@Async marks a method to run on a separate executor. When the scheduler calls an @Async method, Spring submits the work to the executor and returns at once. The scheduler thread is free again after a few microseconds.
You need @EnableAsync to activate it. Put it on any @Configuration class.
@Configuration
@EnableAsync
public class AsyncConfig {
}
@Component
public class SlowJobs {
@Scheduled(fixedRate = 60000)
@Async
public void slowTask() {
// runs on the async executor, so the scheduler thread is free immediately
}
}Spring Boot auto-configures an executor for @Async too. It is separate from the scheduler pool and is configured under spring.task.execution.
Runs can now overlap
Without @Async, the scheduler waits for a method to return before it can start the next run of that method. Overlap is not possible with fixedRate or fixedDelay on the same method.
With @Async, the scheduler never waits. Suppose slowTask above takes 3 minutes and fires every minute. After 3 minutes, three runs are in progress at once. If they write to the same table or file, they can corrupt each other's work.
fixedDelay loses its main purpose here. It measures from the end of the previous run, but the scheduler sees each run end immediately, so the delay is effectively a fixed rate.
Guarding against overlap
A simple guard is an AtomicBoolean. The method skips its work when a previous run is still active.
@Component
public class GuardedJob {
private final AtomicBoolean running = new AtomicBoolean(false);
@Scheduled(fixedRate = 60000)
@Async
public void slowTask() {
if (!running.compareAndSet(false, true)) {
return; // previous run still active, skip this one
}
try {
// long-running work
} finally {
running.set(false);
}
}
}The finally block matters. Without it, one exception would leave the flag set and the job would never run again.
This guard works inside one JVM only. Chapter on multiple instances covers what to do when several copies of the application run.
Common errors
@Asyncdoes nothing. The most frequent causes are a missing@EnableAsync, or calling the method from another method in the same class. Spring applies@Asyncthrough a proxy, so self-invocation bypasses it. A scheduled method is called by the scheduler from outside, so the annotation works there.- The method is not
voidor does not return aFuture. For scheduled methods, keep the return typevoid. - Unbounded queueing. If runs pile up faster than they finish, they queue in the executor. Bound the pool and queue in
spring.task.execution.pooland decide what should happen when it is full. - Lost exceptions. An exception thrown from an
@Asyncvoidmethod does not reach the scheduler. It goes to theAsyncUncaughtExceptionHandler, which logs it by default. Check that your logs show it.
Choosing between a bigger pool and @Async
| Situation | Better choice |
|---|---|
| Several short tasks that sometimes collide | Larger scheduler pool |
| One task that runs for minutes | `@Async`, with an overlap guard |
| A task that must never overlap itself | No `@Async`, so the scheduler enforces it |
Exercise
A method has @Scheduled(fixedDelay = 10000) and @Async. Each run takes 30 seconds. Roughly how many runs are active at once after several minutes, and why?
Show answer
About three. With @Async the scheduler sees each call return immediately, so fixedDelay waits only 10 seconds after the hand-off, not after the work finishes. A new run starts every 10 seconds and each lasts 30, so about three overlap. Fix it by removing @Async or adding an overlap guard such as an AtomicBoolean.