Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 119 ยท Spring Boot

Scheduling, Caching and Async Tasks

Run background jobs with @Scheduled, speed up reads with @Cacheable and run work in parallel with @Async, each rebuilt in plain Java so you understand the pitfalls.

Not everything a backend does is a direct answer to an HTTP request. Some work runs on a schedule: send reminder emails every morning, delete expired sessions every ten minutes. Some results are expensive to compute and worth keeping for a while. And some work should happen in the background so the request can return quickly.

Spring covers these three needs with three annotations: @Scheduled, @Cacheable and @Async. Each one is only a few characters, but each hides a thread pool or a map and comes with traps that bite in production: a scheduler with a single thread, a cache that serves stale data forever, an async method that silently runs synchronously. In this lesson you will build the plain-Java machinery underneath each annotation, run it, and then see the Spring version with the configuration that matters. You should know Spring Beans and Configuration and how proxies work from Aspect-Oriented Programming.

Scheduling tasks

The JDK foundation: ScheduledExecutorService

Java's built-in scheduler is ScheduledExecutorService, created with Executors.newScheduledThreadPool(n). It offers three methods:

  • schedule(task, delay, unit) runs a task once after a delay.
  • scheduleAtFixedRate(task, initialDelay, period, unit) aims for a start every period, measured from the previous start.
  • scheduleWithFixedDelay(task, initialDelay, delay, unit) waits delay after the previous run ends.

The difference only shows when a task is slower than its period. The example runs a 150 ms task with a 100 ms setting both ways and prints when each run starts:

Java Fixed rate versus fixed delay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

With a fixed rate, runs never overlap: when a run is late, the next one starts right after it finishes (0, 150, 300). With a fixed delay there is always a 100 ms pause between runs (0, 250, 500). Use fixed delay for jobs like "poll the outbox table", where piling up runs makes no sense, and fixed rate when you care about a steady cadence, such as sampling a value.

The exception trap

There is a nasty rule in the ScheduledExecutorService documentation: if a periodic task throws an exception, all future runs are silently cancelled. Nothing is logged; the job just stops. The exception is stored in the ScheduledFuture, which nobody looks at.

Java One exception silently stops a periodic task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Spring's scheduler wraps every @Scheduled method in an error handler that logs the exception and keeps the schedule, which is one reason to prefer it. When you use the JDK scheduler directly, always put a try/catch around the body.

@Scheduled in Spring

Enable scheduling once, then annotate methods of any bean. Scheduled methods take no arguments and usually return void:

Java
@Configuration
@EnableScheduling
class SchedulingConfig {}

@Component
class Housekeeping {

    private final SessionRepository sessions;
    private final ReminderService reminders;

    Housekeeping(SessionRepository sessions, ReminderService reminders) {
        this.sessions = sessions;
        this.reminders = reminders;
    }

    @Scheduled(fixedDelay = 10, timeUnit = TimeUnit.MINUTES)
    void deleteExpiredSessions() {
        sessions.deleteExpiredBefore(Instant.now());
    }

    @Scheduled(fixedRateString = "${reminders.poll-interval:PT30S}", initialDelay = 5_000)
    void sendDueReminders() {
        reminders.sendDue();
    }

    @Scheduled(cron = "0 0 7 * * MON-FRI", zone = "Europe/Berlin")
    void morningReport() {
        reminders.sendDailyOverdueReport();
    }
}

Spring cron expressions have six fields, starting with seconds: second minute hour day-of-month month day-of-week. (Unix cron has five, without seconds; copying a five-field expression into Spring is a common startup error.)

Expression Meaning
0 0 7 * * MON-FRI 07:00:00 on weekdays
0 */15 * * * * Every 15 minutes, on the quarter hour
0 0 2 1 * * 02:00 on the first day of every month
0 0 9-17 * * * On the hour from 9:00 to 17:00
@daily Midnight every day (macros @hourly, @weekly, @monthly also work)

Always set zone for business times. Otherwise the server's time zone decides, and that is often UTC in containers.

Two production rules:

  1. The default scheduler has one thread. A slow @Scheduled method delays every other one. Increase it with spring.task.scheduling.pool.size=4, or set spring.threads.virtual.enabled=true so scheduled tasks run on virtual threads.
  2. Every instance runs every job. With three replicas behind a load balancer, morningReport() sends three reports. Use a distributed lock such as ShedLock (a database row acts as the lock), a scheduler with clustering such as Quartz or JobRunr, or move the job to a single scheduled container (a Kubernetes CronJob). Also make jobs idempotent, so running one twice does no harm.

Caching

A cache stores results so that repeated requests skip the expensive work: a slow database query, a remote API call, a heavy computation. Caching is easy to add and hard to get right, because now there are two copies of the truth. The questions to answer are always the same: what is the key, when does an entry expire, how big may the cache grow, and what happens when the data changes?

A memoizing cache with TTL and LRU eviction

The example builds a small cache with:

  • computeIfAbsent-style loading on a miss,
  • a time to live (TTL): entries older than the TTL are reloaded,
  • a maximum size with least-recently-used eviction, using LinkedHashMap in access order and its removeEldestEntry hook,
  • hit and miss statistics,
  • a controllable Clock, so the example can jump forward in time.
Java A TTL and LRU cache with statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After the first six reads, only three went to the "database". Reading key 4 evicted key 1, because 1 was used least recently (3 and 2 were read after it). After the TTL passed, the read of key 2 was a miss again. That is the full life of a cache entry: loaded, hit, expired or evicted, reloaded.

This hand-written version uses one lock for simplicity. Real caches such as Caffeine are lock-free for reads, use smarter eviction (W-TinyLFU), refresh entries in the background, and record statistics for Micrometer. Don't build your own for production.

@Cacheable and friends

Spring's cache abstraction puts this logic in a proxy around your bean, so the business method stays clean:

Java
@Configuration
@EnableCaching
class CacheConfig {}

@Service
class BookService {

    private final BookRepository books;

    BookService(BookRepository books) {
        this.books = books;
    }

    @Cacheable(cacheNames = "books", key = "#id")
    public BookDto findById(long id) {
        return books.findById(id).map(BookDto::from).orElseThrow();
    }

    @Cacheable(cacheNames = "bookSearch", key = "#author + ':' + #page", unless = "#result.isEmpty()")
    public List<BookDto> byAuthor(String author, int page) { ... }

    @CachePut(cacheNames = "books", key = "#result.id()")
    public BookDto rename(long id, String newTitle) { ... }      // always runs, then updates the cache

    @CacheEvict(cacheNames = "books", key = "#id")
    public void delete(long id) { ... }

    @CacheEvict(cacheNames = "bookSearch", allEntries = true)
    public void reindex() { ... }
}
  • @Cacheable checks the cache first and calls the method only on a miss. Without key, the key is built from all arguments.
  • @CachePut always calls the method and stores the result, which keeps the cache fresh after an update.
  • @CacheEvict removes entries; allEntries = true clears a whole cache.
  • condition (checked before the call) and unless (checked after, can see #result) control what gets cached.

Out of the box, Spring Boot uses a simple ConcurrentHashMap cache with no TTL and no size limit. That is fine for demos and dangerous in production. Add Caffeine for a local cache:

PROPERTIES
spring.cache.cache-names=books,bookSearch
spring.cache.caffeine.spec=maximumSize=10000,expireAfterWrite=10m,recordStats

Or add spring-boot-starter-data-redis for a shared cache that all instances see. Local caches are faster (no network) but each instance has its own copy, so an eviction on one instance doesn't reach the others. A short TTL bounds how stale the other copies can get.

Caching pitfalls

  • Self-invocation. Calling this.findById(id) from another method of BookService bypasses the proxy, so nothing is cached. The same trap is explained in Aspect-Oriented Programming.
  • Mutable cached objects. A local cache returns the same object to every caller. If one caller modifies it, everyone sees the change. Cache immutable records or DTOs.
  • Caching entities. JPA entities are tied to a persistence context and may have lazy fields; cache DTOs instead.
  • Cache stampede. When a popular entry expires, hundreds of requests miss at once and all hit the database. @Cacheable(sync = true) lets only one thread load the value while others wait; Caffeine's refreshAfterWrite refreshes it in the background.
  • Caching per-user data under a shared key. Include the user in the key, or don't cache it.
  • No metrics. Without a hit ratio you don't know whether the cache helps. Actuator publishes cache.gets with result=hit|miss when statistics are enabled; see Actuator, Metrics and Observability.

Asynchronous methods

Sometimes a request triggers work the caller doesn't need to wait for, such as sending a confirmation email, or several independent calls that could run at the same time. Java's tool for this is CompletableFuture running on an Executor.

The next example simulates a "book details" page that needs data from three slow sources. Sequential calls add up; parallel calls take as long as the slowest one. It also shows a timeout and a fallback, which you always want when you wait on other systems:

Java Parallel calls with CompletableFuture

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The sequential version takes the sum of the three calls (370 ms, printed rounded down to 50 ms as 350), the parallel one only as long as the slowest call (150 ms). Virtual threads make this pattern cheap: blocking calls are fine, and you can run thousands of them.

completeOnTimeout gives the caller an answer, but the slow task keeps running in the background. For calls to remote systems, also set a timeout on the client itself (for example HttpClient request timeouts), so work is actually abandoned. Microservices covers timeouts, retries and circuit breakers in depth.

@Async in Spring

@Async moves a method call onto an executor. The proxy returns immediately, and the method runs on another thread:

Java
@Configuration
@EnableAsync
class AsyncConfig {}

@Service
class NotificationService {

    @Async
    public void sendLoanConfirmation(long loanId) {          // fire and forget
        mailer.send(templates.loanConfirmation(loanId));
    }

    @Async
    public CompletableFuture<Integer> countOverdue(long memberId) {
        return CompletableFuture.completedFuture(loans.countOverdue(memberId));
    }
}

Spring Boot auto-configures an executor called applicationTaskExecutor: a ThreadPoolTaskExecutor tuned with spring.task.execution.pool.* properties, or a virtual-thread executor when spring.threads.virtual.enabled=true. Name a specific executor with @Async("mailExecutor") to keep slow email work from starving other tasks.

The traps are worth memorizing:

  • Self-invocation again. this.sendLoanConfirmation(id) runs synchronously, because it doesn't go through the proxy. Also, @Async only works on public methods of Spring beans.
  • Exceptions in void methods vanish unless you register an AsyncUncaughtExceptionHandler (by implementing AsyncConfigurer). With a CompletableFuture return type, the exception is stored in the future.
  • The caller's transaction doesn't follow. The async method runs on another thread, outside the caller's @Transactional context. If it reads data the caller just wrote but hasn't committed yet, it won't see it. For "send an email after the loan is saved", publish an event and handle it with @TransactionalEventListener plus @Async, so the email goes out only after commit.
  • Thread-bound context is lost: the security context, MDC log fields and locale. Configure a TaskDecorator that copies them, or use the context-propagation support of Micrometer.
  • It isn't durable. If the instance crashes, queued @Async work is gone. For work that must not be lost, use a message broker, as shown in Messaging with Kafka and RabbitMQ, or an outbox table.

Choosing the right tool

Need Use Avoid
Periodic maintenance on one node @Scheduled with fixed delay Fixed rate for jobs that can be slow
Periodic job in a cluster @Scheduled + ShedLock, Quartz, or a Kubernetes CronJob Plain @Scheduled on every replica
Repeated expensive reads @Cacheable with Caffeine or Redis, TTL and max size The default unbounded map
Parallel independent calls in a request CompletableFuture on virtual threads Sequential blocking calls
Fire-and-forget side effects @Async with an exception handler @Async for work that must survive a crash
Work that must never be lost A message queue or outbox In-memory queues

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A periodic task scheduled with scheduleWithFixedDelay throws an exception on its 3rd run. What happens to the 4th run?

    The JDK suppresses all later runs and stores the exception in the future. Catch exceptions inside the task, or use Spring's scheduler, which logs and continues.
  2. 2. An app with 4 replicas has a @Scheduled(cron = "0 0 7 * * *") job that emails a daily report. How many emails are sent each morning?

    Each instance has its own scheduler. Spring cron has six fields, so the expression is valid. Use ShedLock, Quartz clustering or a single CronJob.
  3. 3. The cache from the lesson has a max size of 3. Keys are read in the order 1, 2, 3, 1, then 4 is loaded. Which key is evicted?

    The LinkedHashMap is in access order, so reading 1 again made it recent. Key 2 had the oldest access and is evicted.
  4. 4. Inside BookService, listFavorites() calls this.findById(id), which is annotated with @Cacheable. What happens?

    Caching, @Async and @Transactional are all applied by proxies. Internal calls on this skip the proxy.
  5. 5. Why is the default Spring Boot cache (without Caffeine or Redis) risky in production?

    The simple ConcurrentHashMap cache never evicts. Configure a provider with TTL and maximum size.

Summary

  • ScheduledExecutorService is the JDK scheduler: fixed rate measures from starts, fixed delay from ends. An uncaught exception silently cancels a periodic task, so catch inside the task.
  • @EnableScheduling + @Scheduled(fixedDelay | fixedRate | cron); Spring cron has six fields (seconds first). Set zone, enlarge the single-thread pool or use virtual threads, and coordinate jobs across replicas.
  • A cache needs a key, TTL, maximum size and an invalidation plan. @Cacheable, @CachePut and @CacheEvict implement read-through caching with proxies; use Caffeine or Redis instead of the unbounded default.
  • Cache immutable DTOs, guard against stampedes (sync = true), and measure the hit ratio.
  • CompletableFuture on virtual threads runs independent calls in parallel; add timeouts and fallbacks.
  • @EnableAsync + @Async runs methods on an executor. Watch for self-invocation, lost exceptions in void methods, missing transaction and security context, and no durability.

Next: Layered Architecture: Controllers, Services and Repositories shows where all these pieces belong in a well-structured application.