简体   繁体   English

Java Spring Async 如何管理线程?

[英]How does Java Spring Async manage threads?

I want to write a Spring Boot application with non-blocking requests in mind.我想编写一个考虑到非阻塞请求的 Spring Boot 应用程序。 In general, my controller methods are single-line methods, which just call a service method and then return, like this:一般来说,我的控制器方法是单行方法,它只是调用一个服务方法然后返回,如下所示:

@RestController
class myController {
    ...
    @GetMapping("/")
    public String getString(){
        return service.getString().get();
    }
}

Let's say I have a Service implementation which looks something like this:假设我有一个 Service 实现,它看起来像这样:

@Service
class myService{
    ...
    @Async
    public CompleteableFuture<String> getString(){
        return "Hello World!";
    }
}

(Assume I have elsewhere included @EnableAsync , and assume the controller code is modified to handle CompleteableFutures by extracting the String value and returning it) (假设我在其他地方包含了@EnableAsync ,并假设控制器代码被修改为通过提取 String 值并返回它来处理 CompleteableFutures )

When my controller calls my service, does Java still reserve a worker thread to wait on the return value from the Service, or is the worker thread returned to the thread pool until the service completes its work?当我的控制器调用我的服务时,Java 是否仍然保留一个工作线程来等待服务的返回值,还是工作线程返回到线程池直到服务完成其工作?

Thanks.谢谢。

When my controller calls my service, does Java still reserve a worker thread to wait on the return value from the Service当我的控制器调用我的服务时,Java 是否仍然保留一个工作线程来等待来自服务的返回值

No, your controller does not wait, the method @Async method is called asynchronously.不,您的控制器不会等待, @Async方法被异步调用。

or is the worker thread returned to the thread pool until the service completes its work?还是工作线程返回到线程池,直到服务完成其工作?

By default when @Async method is called Spring uses SimpleAsyncTaskExecutor which starts a new thread for each invocation, so no thread pool is used.默认情况下,当@Async方法被调用时,Spring 使用SimpleAsyncTaskExecutor为每次调用启动一个新线程,因此不使用线程池。 You can however provide your own Task Executor or use ThreadPoolTaskExecutor - details .但是,您可以提供自己的 Task Executor 或使用ThreadPoolTaskExecutor - details

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

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