我从未真正使用过 Java 异步编程,并且对实践是否是最好的做法感到非常困惑。
我得到了这个方法
public static CompletableFuture<Boolean> restoreDatabase(){
DBRestorerWorker dbWork = new DBRestorerWorker();
dbWork.run();
return "someresult" ;
}
然后这个调用第一个
@POST
@Path("{backupFile}")
@Consumes("application/json")
public void createOyster(@PathParam("backupFile") String backupFile) {
RestUtil.restoreDatabase("utv_johan", backupFile);
//.then somemethod()
//.then next method()
}
我想做的是首先调用restoreDatabase()方法,该方法调用dbWork.run()(这是一个void方法),当该方法完成时,我希望createOyster执行下一个方法,依此类推,直到我完成完成了所有需要的步骤。有人得到了一个指导方针,就是从这个开始。在当今的 Java 中,哪种做法最好?
最佳答案
由于您已经使用了CompletableFuture
,因此您可以像这样构建异步执行管道。
CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
DBRestorerWorker dbWork = new DBRestorerWorker();
dbWork.run();
return "someresult";
};
}).thenComposeAsync((Function<String, CompletionStage<Void>>) s -> {
CompletableFuture<String> future = new CompletableFuture<>();
try{
//createOyster
future.complete("oyster created");
}catch (Exception ex) {
future.completeExceptionally(ex);
}
return null;
});
如您所见,您可以调用 thenComposeAsync
或 thenCompose
来构建 CompletionStage
链并使用前面的结果执行任务如果您没有任何东西可归还,请执行步骤或设为 Void。
这是一个非常好的guide
关于java - java 中使用 void 方法的异步编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49552504/