1

I'm new in software. I'm working to understand async programming in Spring Boot. As seen above, I set thread pool size 2. When I requested same url three times one after another. My two requests are working asynchronously. Third one is waiting. This is ok. But when I don't use the asynchronous feature (neither @async annotation nor threadpool), it still performs transactions asynchronously, as before. So I'm confused. Spring Boot rest controller behaves asynchronously by default? Why we use @async in Spring Boot? Or do I misunderstand that?

@Service
public class TenantService {
    @Autowired
    private TenantRepository tenantRepository;

    @Async("threadPoolTaskExecutor")
    public Future<List<Tenant>> getAllTenants() {
        System.out.println("Execute method asynchronously - "
                + Thread.currentThread().getName());
        try {
            List<Tenant> allTenants = tenantRepository.findAll();

            Thread.sleep(5000);

            return new AsyncResult<>(allTenants);
        } catch (InterruptedException e) {
            //
        }
        return null;
    }
}
@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsynchThread-");
        executor.initialize();
        return executor;
    }

    @Bean(name = "threadPoolTaskExecutor2")
    public Executor threadPoolTaskExecutor2() {
        return new ThreadPoolTaskExecutor();
    }
}

1 Answer 1

3

I'm assuming you are using the default embedded Tomcat from Spring Boot. If that's the case, then you are not misunderstanding. Tomcat will indeed work asynchronously by default, meaning it will start a new thread for every request (see this for on that).

The @Async annotation does not aim to replace the functionality that Tomcat provides in this case. Instead, that annotation allows executing any method of a bean in a separate thread. For your particular use case, it might be enough to let Tomcat start a new thread for every request, but sometimes you might want to parallelize work further.

An example on when you would probably want to use both is when a request must trigger some heavy computation, but the response does not depend on it. By using the @Async annotation, you can start the heavy computation on another thread, and let the request finish sooner (effectively allowing the server to handle other requests while the heavy computation runs independently on another thread).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks your answer. I wanted to understand why Spring boot behaves asynchronously although I didn't use async and thread pool. I learned it because embedded Tomcat provides asynchronous operation for requests. I got it. Then, Can I say I will not use Async if there is no heavy operation in the background, there is just requests for querying database and returning data?
I'm glad I could help! You can find many other use cases for the Async annotation, apart from heavy operations in the background. One other example would be when for the same request you must execute 2 (or more) database queries that are independent. You can execute all those queries in parallel using Async and await their completion before finally computing the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.