Spring Framework
@Async
Spring Boot
Java Configuration
Asynchronous Programming

Spring Async without xml config

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Spring asynchronous execution no longer requires XML configuration. With Java config and annotations, you can enable @Async behavior cleanly in Spring Boot or standard Spring applications. The core pieces are @EnableAsync, an executor bean, and async methods that are invoked through Spring proxies.

The common failures are usually architectural: self-invocation bypassing proxies, missing executor configuration, or hidden blocking work that nullifies async benefits. This guide covers a robust setup.

Core Sections

1) Enable async with Java configuration

java
1import org.springframework.context.annotation.Configuration;
2import org.springframework.scheduling.annotation.EnableAsync;
3
4@Configuration
5@EnableAsync
6public class AsyncConfig {
7}

This activates Spring’s async infrastructure and proxying behavior.

2) Define a dedicated executor

Relying on default executor can produce unpredictable behavior under load. Define one explicitly.

java
1import java.util.concurrent.Executor;
2import org.springframework.context.annotation.Bean;
3import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
4
5@Bean(name = "appTaskExecutor")
6public Executor appTaskExecutor() {
7    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
8    executor.setCorePoolSize(8);
9    executor.setMaxPoolSize(32);
10    executor.setQueueCapacity(500);
11    executor.setThreadNamePrefix("async-app-");
12    executor.initialize();
13    return executor;
14}

3) Annotate service methods with @Async

java
1import java.util.concurrent.CompletableFuture;
2import org.springframework.scheduling.annotation.Async;
3import org.springframework.stereotype.Service;
4
5@Service
6public class ReportService {
7
8    @Async("appTaskExecutor")
9    public CompletableFuture<String> generateReport(String id) {
10        String report = expensiveWork(id);
11        return CompletableFuture.completedFuture(report);
12    }
13}

Return CompletableFuture when callers need results, otherwise void for fire-and-forget tasks.

4) Handle exceptions explicitly

For async methods returning CompletableFuture, propagate errors with exceptionally/handle patterns. For void async methods, register AsyncUncaughtExceptionHandler.

java
1import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
2import org.springframework.scheduling.annotation.AsyncConfigurer;
3
4@Configuration
5public class AsyncErrorConfig implements AsyncConfigurer {
6    @Override
7    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
8        return (ex, method, params) -> {
9            // central logging/alerting
10        };
11    }
12}

5) Understand proxy limits

@Async works only when method calls go through Spring proxy. A method calling another @Async method in the same class is self-invocation and runs synchronously.

Design pattern: keep async entrypoints in separate beans or inject proxy to call across bean boundaries.

6) Production checklist

Tune pool sizes based on workload type. I/O-heavy tasks tolerate higher concurrency; CPU-heavy tasks should stay near core counts. Add metrics for queue depth, active threads, task rejection, and execution time. Configure rejection policy intentionally so overload is visible.

Finally, verify transactional boundaries. Async methods run in separate threads and do not automatically share caller transaction context.

7) Production checklist for Spring async execution

Treat this topic as an operational concern, not only a coding snippet. Start by defining one explicit success metric that reflects business behavior, such as failed request rate, pipeline lag, model quality drift, or user-visible latency. Then create a small acceptance checklist that can run in both staging and production-like test environments. The checklist should verify the happy path, at least one failure path, and one boundary case.

Capture configuration assumptions close to the implementation, including timeouts, versions, environment variables, and external dependencies. If behavior varies by environment, encode those differences in configuration rather than hardcoded branches. Add lightweight observability from day one: key counters, error categorization, and structured logs with identifiers that support correlation during incident response.

Finally, define rollback and ownership before rollout. Decide who responds to alerts, what threshold should trigger rollback, and which fallback mode keeps the system functional if this component degrades. A clear ownership and rollback plan turns isolated technical knowledge into a maintainable production practice.

Common Pitfalls

  • Enabling @Async but relying on default executor behavior in production.
  • Expecting async behavior during self-invocation inside the same bean.
  • Running blocking operations in small thread pools and creating queue buildup.
  • Ignoring exception handling for void async methods.
  • Assuming transaction/security context is automatically propagated to async tasks.

Summary

Spring async without XML is clean and powerful with @EnableAsync, explicit executors, and well-structured service boundaries. Most reliability issues come from proxy semantics and operational tuning, not annotation syntax. Treat async as an execution architecture decision, and back it with metrics and clear failure handling.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.