ixxbcrl
ixxbcrl

Reputation: 5

Spring @Async on a Singleton Bean

I'm currently quite confused about the difference between Spring's @Async and how a Singleton Bean is being handled with respect to concurrent requests.

I have read a very insightful explanation in question (How does the singleton Bean serve the concurrent request?). But I would like to expand further based on the 2nd answer.

The answer states that "In short a stateless singleton will be able to serve two requests concurrently because they will be in different threads.".

If this were true, then what is the point of Spring's @Async, which from Spring's tutorial (https://spring.io/guides/gs/async-method/) states: The findUser method is flagged with Spring’s @Async annotation, indicating it will run on a separate thread.?

Am I right to say that the Singleton Beans handle concurrent requests on separate threads, whereas @Async handles how a single request is processed across different threads?

If that is so, how do I configure the pool of threads used by my web application?

Upvotes: 0

Views: 1664

Answers (1)

Mick
Mick

Reputation: 973

A singleton bean can be used by many parallel (request) threads. You wouldn't call this asynchrony. Each of your parallel threads would be executed on one serial execution path.

However, you might be executing a request and during this request you would like to send an email. This involves talking to the mail server. Your Java mail API might force you to wait for the response - which you might try to avoid. You would then annotate some "sendEmail" method with @Asnc and Spring would take care of firing up a second thread to process this method. However - the calling process would not wait for this "asynchronous" task.

Spring handles request processing with a thread pool by default to avoid the cost of constructing new threads. I guess, for @Async, you would need to configure a thread pool yourself (Spring @Async limit number of threads)

Upvotes: 1

Related Questions