简体   繁体   English

在Singleton Bean上使用Spring @Async

[英]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. 我目前对Spring的@Async与如何处理并发请求的Singleton Bean之间的差异感到困惑。

I have read a very insightful explanation in question ( How does the singleton Bean serve the concurrent request? ). 我已经阅读了一个非常有见地的解释( 单例Bean如何满足并发请求? )。 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. 如果这是真的,那么Spring的@Async有什么意义,根据Spring的教程( https://spring.io/guides/gs/async-method/ )指出: findUser方法带有Spring的@Async注释,指示它将在单独的线程上运行。 ?

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? 我说对了,Singleton Beans处理不同线程上的并发请求 ,而@Async处理不同线程上的单个请求的处理方式吗?

If that is so, how do I configure the pool of threads used by my web application? 如果是这样,如何配置Web应用程序使用的线程池?

A singleton bean can be used by many parallel (request) threads. 一个单例bean可以被许多并行(请求)线程使用。 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. 您的Java邮件API可能会迫使您等待响应-您可能会尝试避免这种响应。 You would then annotate some "sendEmail" method with @Asnc and Spring would take care of firing up a second thread to process this method. 然后,您可以使用@Asnc注释某些“ sendEmail”方法,Spring会启动第二个线程来处理该方法。 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. Spring默认情况下使用线程池处理请求处理,以避免构建新线程的开销。 I guess, for @Async, you would need to configure a thread pool yourself ( Spring @Async limit number of threads ) 我猜想,对于@Async,您需要自己配置一个线程池( Spring @Async限制线程数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM