CompletableFuture.runAsync 是否有线程限制

Pra*_*eep 3 java multithreading asynchronous threadpool completable-future

我有一个 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);
                        }
                    });
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

Kha*_*111 5

您遇到的是ForkJoinPool.commonPool().

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

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

Runtime.getRuntime().availableProcessors() - 1
Run Code Online (Sandbox Code Playgroud)

您可以更新尺寸:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=8
Run Code Online (Sandbox Code Playgroud)

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