Java CompletableFuture分配执行器
我对未来遗嘱执行人的定义感到困惑。我不知道如何告诉CompletableFuture在特定的执行者中运行它。提前谢谢Java CompletableFuture分配执行器,java,asynchronous,executorservice,completable-future,concurrent.futures,Java,Asynchronous,Executorservice,Completable Future,Concurrent.futures,我对未来遗嘱执行人的定义感到困惑。我不知道如何告诉CompletableFuture在特定的执行者中运行它。提前谢谢 //Suppose I have an executor ExecutorService myExecutor=Executors.newFixedThreadPool(2); //If I create a future like this CompletableFuture.runAsync(() -> { //Do something }, myExec
//Suppose I have an executor
ExecutorService myExecutor=Executors.newFixedThreadPool(2);
//If I create a future like this
CompletableFuture.runAsync(() -> {
//Do something
}, myExecutor); // I can put the executor here and say the future to this executor
//But I do not know where to put executor if I create my future in method style like this
private final CompletableFuture<Void> myMethod(String something) {
//Do something
return null;
}
//and use it like this
.thenCompose(this::myMethod); //How can I specify the executor in this case?
//假设我有一个执行者
ExecutorService myExecutor=Executors.newFixedThreadPool(2);
//如果我创造这样的未来
CompletableFuture.runAsync(()->{
//做点什么
},myExecutor);//我可以把遗嘱执行人放在这里,对遗嘱执行人说未来
//但若我以这样的方式创造我的未来,我不知道把执行者放在哪里
私有最终CompletableFuture myMethod(字符串){
//做点什么
返回null;
}
//像这样使用它
.thenCompose(此::myMethod)//在这种情况下,我如何指定执行人?
您可以执行以下操作:
ExecutorService es = Executors.newFixedThreadPool(4);
List<Runnable> tasks = getTasks();
CompletableFuture<?>[] futures = tasks.stream()
.map(task -> CompletableFuture.runAsync(task, es))
.toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();
es.shutdown();
Executors服务=Executors.newFixedThreadPool(4);
List tasks=getTasks();
CompletableFuture[]futures=tasks.stream()
.map(任务->CompletableFuture.runAsync(任务,es))
.toArray(可完成的未来[]::新);
CompletableFuture.allOf(futures.join();
es.shutdown();
在您的示例中,有3个可完成的未来
正在发挥作用:
runAsync()
myMethod()
thencomose()返回的
runAsync()
的将在给定的执行器上执行,并处理future 1李>
thencomose()
调用myMethod()
以创建future 2的方法可以在任何执行器上运行,使用thencomoseasync()
显式选择一个李>
myMethod()
返回的future 2的一个–这将在myMethod()
本身内部控制李>
thencomose()
返回的future 3的一个–这是内部处理的,取决于执行顺序(例如,如果myMethod()
返回一个已经完成的future,它也将完成前者)如您所见,其中涉及多个任务和执行器,但您始终可以使用
*Async()
变量控制从属阶段中使用的执行器。唯一不能真正控制它的情况是第4种情况,但只要相关阶段也使用*Async()
变体,它就是一种廉价的操作。这很有趣。这是唯一的办法吗?OP似乎试图先创建一种复合的CompletableFuture
,然后提交它。然而,您首先将单个CompletableFutures
,然后将它们组合成一个更大的“虚拟”未来对象。OP的方法可行吗?(当我查看API时,它似乎不是。)您是否在询问如何在executor中运行myMethod
,这与使用thencoseasync一样简单代码>而不是然后编写
, 或者你是在问如何控制myMethod
中发生的关于返回的未来的事情,这是不可能的?