最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - CompletableFuture not using defined TaskExecutor. Using commonPool instead - Stack Overflow

programmeradmin0浏览0评论

I'm trying execute some async work using CompletableFuture with a custom Executor. However, I see from the logs that it's using the default commonPool. What am I missing here?

@Async("datasetTaskExecutor")
public CompletableFuture<DatasetResponse> getTplDataset(String datasetId) {
    return CompletableFuture
        .supplyAsync(() -> restTemplate.getForObject(BASE_PATH, DatasetResponse.class, datasetId));
}

...

@Bean
public TaskExecutor datasetTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(8);
    executor.setMaxPoolSize(40);
    executor.setThreadNamePrefix("DatasetExecutor-");
    executor.initialize();
    return executor;
}

I'm trying execute some async work using CompletableFuture with a custom Executor. However, I see from the logs that it's using the default commonPool. What am I missing here?

@Async("datasetTaskExecutor")
public CompletableFuture<DatasetResponse> getTplDataset(String datasetId) {
    return CompletableFuture
        .supplyAsync(() -> restTemplate.getForObject(BASE_PATH, DatasetResponse.class, datasetId));
}

...

@Bean
public TaskExecutor datasetTaskExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(8);
    executor.setMaxPoolSize(40);
    executor.setThreadNamePrefix("DatasetExecutor-");
    executor.initialize();
    return executor;
}
Share Improve this question edited Jan 21 at 16:17 Ryuzaki L 40.1k14 gold badges77 silver badges108 bronze badges asked Jan 21 at 11:42 Jacob LJacob L 1533 silver badges21 bronze badges 2
  • 1 Because it is first executed with the datasetTaskExecutor, then due to the supplyAsync passed to the regular pool. The problem is your own code. Just call the resttemplate in your method and return the result as CompletedFuturepletedFuture(result). – M. Deinum Commented Jan 21 at 12:23
  • @M.Deinum That was it, thank you. – Jacob L Commented Jan 23 at 1:47
Add a comment  | 

1 Answer 1

Reset to default 0

The CompletableFuture.supplyAsync() method executes the provided Supplier function in a separate thread, typically from the ForkJoinPoolmonPool by default.

You can provide a custom Executor to override the default behavior:

public CompletableFuture<DatasetResponse> getTplDataset(String datasetId) {
    return CompletableFuture
            .supplyAsync(() -> restTemplate.getForObject(BASE_PATH, DatasetResponse.class, datasetId), **datasetTaskExecutor**);
}
发布评论

评论列表(0)

  1. 暂无评论