我想在我的 spring boot 项目中使用 ForkJoinPool 和 @Async 注释,比如 ThreadPoolTaskExecutor
例如:-
@Bean("threadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(1000);
executor.setThreadNamePrefix("Async-");
return executor;
}
我用 https://dzone.com/articles/spring-boot-creating-asynchronous-methods-using-as这个链接在我的代码中,但我想像这样使用 ForkJoinPool。
最佳答案
异步使用 ForkJoinPool 没问题。这种方法并不完全是 ForkJoinPool 的设计目的 - 它解决分而治之的任务并使用工作窃取算法,但执行事件式或 IO 阻塞任务,这是一个有效的用例。
因此,通过基本用法,您可以:
CompletableFuture.runAsync(() -> doSomething(), ForkJoinPool.commonPool());
您还可以在异步模式下创建自定义 ForkJoinPool。异步模式下 ForkJoinPool 中的工作人员以 FIFO(先进先出)顺序处理任务。默认情况下,ForkJoinPools 以 LIFO(后进先出)顺序处理此类任务。此外,异步模式设置仅涉及从未加入的 fork 任务。可用于已提交但从未加入的事件式任务(执行它们的副作用的任务,而不是返回将由 fork 任务处理然后加入的结果)。
您可以像这样在异步模式下创建具有给定并行度的自定义 ForkJoinPool(第一个参数是池大小,最后一个 - bool asyncMode):
ForkJoinPool pool = new ForkJoinPool(
6, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
那么你所追求的是:
@Bean("threadPoolTaskExecutor")
public Executor getAsyncExecutor() {
ForkJoinPool pool = new ForkJoinPool(
6, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true);
return pool;
}
关于java - 如何在 Spring Boot @Async 中使用 ForkJoinPool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54365130/