【问题标题】:Is there any thread limit on CompletableFuture.runAsyncCompletableFuture.runAsync 是否有任何线程限制
【发布时间】:2021-06-25 21:29:08
【问题描述】:

我有一个 Rest api,它在其中调用如下所示的异步调用

 CompletableFuture.runAsync(() -> {
                        // method call or code to be async.
                     try {
                            logger.info("======Before Async method call======with studySchemaEventId: "+enrollmentStudySchemaEventId);
                            this.performSimulation(studyId, enrollmentStudySchemaEventId, cloneOfFile, simulationRunInfo, totalAccrual);
                            logger.info("======After Async method call======with studySchemaEventId: "+enrollmentStudySchemaEventId);
                        } catch (SimulationException e) {
                            logger.error("Error running Async call for performSimulation()", e);
                        }
                    });

当我调用 Rest api 时,它正确执行了异步调用。 但是我有一个案例,我调用了 4 次 Rest Api,它执行了 3 次异步调用,而对于第 4 次 Api 调用,我没有看到调用了 Async 方法。

runAsync() 调用是否有任何限制?或者为什么在 3 次调用后不调用 Async 方法?

这是 Rest API 调用:

    @POST
    @Path("/trigger")
    @Consumes(MediaType.MULTIPART_FORM_DATA)  
    @ApiOperation(value = "Trigger Simulation",  tags = "Study Event Simulation")
    public Response triggerSimulation( 
            @FormDataParam("file") InputStream file,
            @FormDataParam("file") FormDataContentDisposition fileDetail ,
            @FormDataParam("simulationRunInfo") SimulationRunInfo simulationRunInfo
  
    ) 
    {

// some other logic
// Async code here

}

【问题讨论】:

  • 这4个电话你是怎么写的?可以附上代码吗?
  • 更新代码@polypiel

标签: java multithreading asynchronous threadpool completable-future


【解决方案1】:

你遇到的是ForkJoinPool.commonPool()中配置的线程数。

分配给runAsSync 的任务由ForkJoinPool.commonPool() 完成。此池是根据主机中的内核数配置的。看来你有 4 个核心。

默认情况下,公共池的大小:

Runtime.getRuntime().availableProcessors() - 1

您可以更新尺寸:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=8

或者,您可以将重载的 runAsSync 与 executors 参数一起使用。

【讨论】:

  • 你的意思是我可以通过一些固定的线程限制,如下所示:ExecutorService executor = Executors.newFixedThreadPool(15);
  • 您可以这样做,也可以使用系统参数 -XX:ActiveProcessorCount=8。注意:您最终必须了解主机和工作量的限制。
  • 当然让我试试。我的本地工作没有任何配置。但我部署在 DEV 服务器上,我遇到了这个问题
  • 它也应该第四次调用。可以延迟,但应该。调用代码是什么样的?
  • 我接受了一些代码有效的答案。在 UI 上,我们有调用端点的按钮。
猜你喜欢
  • 2018-12-08
  • 1970-01-01
  • 2011-10-04
  • 2021-11-26
  • 1970-01-01
  • 2015-11-09
  • 2016-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多