我有一个使用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配置为它的线程池中只有一个线程,所以对于所有3个请求,它使用的是http-nio-9191-exec-1,,但由于我使用的是CompletableFuture,所以它使用的是不同的线程(例如,处理异步任务的ForkJoinPool.commonPool-worker-2) )。从哪里开始使用新线程?因为在tomcat线程池中只有一个线程可用。
发布于 2020-11-06 16:12:14
supplyAsync方法文档指出:
返回一个新的CompletableFuture,该任务由运行在ForkJoinPool.commonPool()中的任务异步完成,该任务的值是通过调用给定的供应商获得的。
公共池由JVM创建,它在ForkJoinPool API doc中进行了描述。
静态commonPool()是可用的,适合于大多数应用程序。没有显式提交到指定池的任何ForkJoinTask都使用公共池。使用公共池通常会减少资源使用(它的线程在不使用期间被缓慢地回收,并在以后使用时恢复)。
因为这个池不是由Tomcat创建的,所以最大线程限制不适用。
https://stackoverflow.com/questions/64717835
复制相似问题