更具体地说,在这两段代码中有什么区别,一个返回void
,另一个返回CompletionStage<Void>
?
使用void
或CompletionStage<Void>
中的一个相对于另一个有什么优势?
在代码示例2中,我没有使用x
中的变量thenCompose
。有更好的书写方式吗?
如果我在函数boolean
中返回一个doValidation
并检查true
函数中的performTask
是更好的做法吗?
代码示例1:
public CompletionStage<Response> performTask(Request request) throws MyException {
doValidation(request);
return service.performTask(request).thenCompose(serviceResponse -> CompletableFuture.completedFuture(buildMyResponse(serviceResponse)));
}
private void doValidation(Request request) throws MyException {
CompletableFuture.runAsync(() -> {
// Validate
if (*someCondition*) {
throw new MyException(.....);
}
});
}
代码示例2:
public CompletionStage<Response> performTask(Request request) throws MyException {
return doValidation(request).thenCompose(x -> {
return service.performTask(request).thenCompose(serviceResponse -> CompletableFuture.completedFuture(buildMyResponse(serviceResponse)));
});
}
private CompletionStage<Void> doValidation(Request request) throws MyException {
return CompletableFuture.runAsync(() -> {
// Validate
if (*someCondition*) {
throw new MyException(.....);
}
});
}
最佳答案
我正在解决你的第一个问题
What advantages of using one of void or CompletionStage<Void> over the other?
要了解差异,您应该尝试记录流。它将帮助您确定两者的工作方式有何不同。
这是一个与您遵循的方法类似的示例。我提出了自己的示例,因为我不知道您的代码。
public class Test {
public static void main(String[] args) {
tryWithVoid();
// tryWithCompletionStageVoid();
}
public static void tryWithVoid() {
System.out.println("Started");
validate(null);
System.out.println("Exit");
}
public static void tryWithCompletionStageVoid() {
System.out.println("Started");
validateCS(null).thenRun(() -> System.out.println("Validation complete"));
System.out.println("Exit");
}
public static CompletionStage<Void> validateCS(String val) {
return CompletableFuture.runAsync(() -> {
if (val == null) {
System.out.println("Validation failed! value is null");
}
});
}
public static void validate(String val) {
CompletableFuture.runAsync(() -> {
if (val == null) {
System.out.println("Validation failed! value is null");
}
});
}
}
如果运行
tryWithVoid()
,您将看到输出为:Started
Exit
Validation failed! value is null
而当您运行
tryWithCompletionStageVoid()
时,它将是:Started
Validation failed! value is null
Validation complete
Exit
在第一种方法
tryWithVoid()
中,它不等待操作完成。因此,该操作的结果对于调用之后的代码可能有用,也可能不可用。但是,在第二种方法
tryWithCompletionStageVoid()
中,它在运行下一阶段之前等待该阶段完成。如果您在各个阶段之间没有依赖性,则可以使用
void