[英]Why CompletableFuture 's thenAccept() not running on the main thread
I process the long running operation inside the CompletableFuture's supplyAsync() and get the result into thenAccept(). 我在CompletableFuture的supplyAsync()中处理长时间运行的操作,并将结果输入thenAccept()。 In some times thenAccept() perform on the main thread but some time it running on the worker thread.But I want run thenAccept() operation only on the main thread.
在某些时候,然后接受()执行主线程但有时它在工作线程上运行。但是我想在主线程上运行thenAccept()操作。 this is the sample code.
这是示例代码。
private void test() {
ExecutorService executorService = Executors.newSingleThreadExecutor();
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync | I am running on : " + Thread.currentThread().getName());
return "Hello world";
}, executorService);
CompletableFuture<Void> cf3 = cf1.thenAccept(s -> {
System.out.print("thenAccept | I am running on : " + Thread.currentThread().getName());
System.out.println(" | answer : " + s);
});
cf3.thenRun(() -> {
System.out.println("thenRun | I am running on : " + Thread.currentThread().getName());
System.out.println();
});
}
public static void main(String[] args) {
App app = new App();
for(int i = 0; i < 3; i++){
app.test();
}
}
result is : 结果是:
supplyAsync | I am running on : pool-1-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main
supplyAsync | I am running on : pool-2-thread-1
thenAccept | I am running on : main | answer : Hello world
thenRun | I am running on : main
supplyAsync | I am running on : pool-3-thread-1
thenAccept | I am running on : pool-3-thread-1 | answer : Hello world
thenRun | I am running on : pool-3-thread-1
How can i fix this ? 我怎样才能解决这个问题 ?
Take a look in the JavaDoc of CompletableFuture . 看一下CompletableFuture的JavaDoc。 The interesting part is the one about the CompletionStage policies.
有趣的部分是关于CompletionStage政策的部分。
There you find that using the non-async method results in a kind of either-or-scenario. 在那里,您会发现使用非异步方法会产生一种或者一种情况。 If you then take a look in the implementation you will end up in the non-public part of the Java Runtime.
如果您随后查看实现,您将最终进入Java Runtime的非公共部分。 There is some UNSAFE handling that implies that there may happen some kind of race condition.
有一些UNSAFE处理意味着可能会发生某种竞争条件。
I would suggest using thenAcceptAsync() and thenRunAsync() variants and pass your executorService variable to both calls. 我建议使用thenAcceptAsync()和thenRunAsync()变体,并将executorService变量传递给两个调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.