繁体   English   中英

在配置tomcat只使用1个线程时,使用completablefuture进行异步处理时,它使用另一个线程如何?

[英]While configuring tomcat to use only 1 thread, when using completablefuture for async processing, it is using another thread how?

我有一个使用 CompletableFuture 进行异步处理的端点,并且我已将嵌入式 tomcat 配置为只有一个线程,如下所示:

server.tomcat.max-threads=1

我的端点如下:

@RequestMapping(path = "/asyncCompletable", method = RequestMethod.GET)
public CompletableFuture<String> getValueAsyncUsingCompletableFuture() {
    log.info("Request received");
    CompletableFuture<String> completableFuture
            = CompletableFuture.supplyAsync(this::processRequest);
    log.info("Servlet thread released");
    return completableFuture;
}

在浏览器中多次(例如同时3次)点击端点时,控制台日志如下:

19:20:19.234 [http-nio-9191-exec-1] Request received 
19:20:19.234 [http-nio-9191-exec-1] Servlet thread released 
19:20:19.234 [ForkJoinPool.commonPool-worker-0] Start processing request 
19:20:19.839 [http-nio-9191-exec-1] Request received 
19:20:19.859 [http-nio-9191-exec-1] Servlet thread released 
19:20:19.859 [ForkJoinPool.commonPool-worker-1] Start processing request 
19:20:20.595 [http-nio-9191-exec-1] Request received 
19:20:20.596 [http-nio-9191-exec-1] Servlet thread released 
19:20:20.596 [ForkJoinPool.commonPool-worker-2] Start processing request 
19:20:24.235 [ForkJoinPool.commonPool-worker-0] Completed processing request 
19:20:24.235 [ForkJoinPool.commonPool-worker-0] Start reversing string 
19:20:24.235 [ForkJoinPool.commonPool-worker-0] Completed reversing string 
19:20:24.860 [ForkJoinPool.commonPool-worker-1] Completed processing request 
19:20:24.860 [ForkJoinPool.commonPool-worker-1] Start reversing string 
19:20:24.860 [ForkJoinPool.commonPool-worker-1] Completed reversing string 
19:20:25.596 [ForkJoinPool.commonPool-worker-2] Completed processing request 
19:20:25.597 [ForkJoinPool.commonPool-worker-2] Start reversing string 

如您所见,由于我已将 tomcat 配置为在其线程池中只有 1 个线程,因此对于所有 3 个请求,它都使用http-nio-9191-exec-1 ,但由于我使用的是 CompletableFuture,因此它使用的是不同的线程(例如 ForkJoinPool.commonPool-worker-2 )来处理异步任务。 它从哪里使用新线程? 因为我在 tomcat 线程池中只有一个线程可用。

supplyAsync方法文档说:

返回一个新的 CompletableFuture,它由在 ForkJoinPool.commonPool() 中运行的任务异步完成,其值是通过调用给定的供应商获得的。

公共池由 JVM 创建,在ForkJoinPool API doc 中有描述:

静态 commonPool() 可用并且适用于大多数应用程序。 公共池由未明确提交到指定池的任何 ForkJoinTask 使用。 使用公共池通常会减少资源使用(其线程在不使用期间缓慢回收,并在后续使用时恢复)。

由于此池不是由 Tomcat 创建的,因此最大线程限制不适用。

暂无
暂无

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

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