May*_*yur 9 java multithreading spring-boot completable-future
I have been working on Java CompletableFuture lately and found , we should always use customized Threadpool. With it, I found two ways of passing threadpool to existing code. Like below
This is my ThreadPool in configuration file
@Override
@Bean(name = "commonThreadPool")
public Executor getAsyncExecutor() {
return new ThreadPoolTaskExecutor();
}
Run Code Online (Sandbox Code Playgroud)
1. Passing existingThreadPool in argument.
@Autowired
@Qualifier("commonThreadPool")
TaskExecutor existingThreadPool;
CompletableFuture.runAsync(() -> executeTask(),existingThreadPool);
Run Code Online (Sandbox Code Playgroud)
2. Using async like below
@Async("commonThreadPool")
public void executeTask() {
// Execute Some Task
}
Run Code Online (Sandbox Code Playgroud)
is there any third way where I can write CompletableFuture Handler or Override its existing behaviour at single place where I can pass custom Threadpool. And after that wherever I use below code, it should pick my existing ThreadPool instead of forkJoin pool.
CompletableFuture.runAsync(() -> executeTask());
Run Code Online (Sandbox Code Playgroud)
没有为所有CompletableFuture实例替换默认执行程序的标准方法。但是从 Java 9 开始,您可以为子类定义默认执行程序。例如与
public class MyCompletableFuture<T> extends CompletableFuture<T> {
static final Executor EXEC = r -> {
System.out.println("executing "+r);
new Thread(r).start();
};
@Override
public Executor defaultExecutor() {
return EXEC;
}
@Override
public <U> CompletableFuture<U> newIncompleteFuture() {
return new MyCompletableFuture<>();
}
public static CompletableFuture<Void> runAsync?(Runnable runnable) {
Objects.requireNonNull(runnable);
return supplyAsync(() -> {
runnable.run();
return null;
});
}
public static <U> CompletableFuture<U> supplyAsync?(Supplier<U> supplier) {
return new MyCompletableFuture<U>().completeAsync(supplier);
}
}
Run Code Online (Sandbox Code Playgroud)
您执行了所有必要步骤,为MyCompletableFuture. executor hold inEXEC仅用作示例,使用时会产生打印输出,因此当您使用该示例类时
MyCompletableFuture.supplyAsync(() -> "test")
.thenApplyAsync(String::toUpperCase)
.thenAcceptAsync(System.out::println);
Run Code Online (Sandbox Code Playgroud)
它会打印
executing java.util.concurrent.CompletableFuture$AsyncSupply@65ab7765
executing java.util.concurrent.CompletableFuture$UniApply@119d7047
executing java.util.concurrent.CompletableFuture$UniAccept@404b9385
TEST
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5605 次 |
| 最近记录: |