在涉及早期返回时将阻止代码转换为非阻塞

时间:2018-03-14 22:52:25

标签: java-8 playframework-2.0 nonblocking completable-future completion-stage

我正在尝试转换阻塞的Play框架控制器操作,如下所示:

public Result testSync(String param1, String param2) {

    String result1 = <LONG-DB-QUERY>;
    if (result1 == null) {
        return internalServerError();
    }

    if (result1.equals("<SOME VALUE>")) {
        return ok(param1);
    }

    String result2 = <LONG-DB-QUERY>;
    return ok(result1 + result2);
}

使用Future接口进入非阻止代码,即返回CompletionStage<Result>

如您所见,我需要result1result2。我假设我无法使用supplyAsyncthenCombine,因为只有在某些情况下才需要计算result2

1 个答案:

答案 0 :(得分:1)

好的,基于similar answer这就是我设法做到的方式:

public CompletionStage<Result> testAsync(String param1, String param2) {

    CompletableFuture<Result> shortCut = new CompletableFuture<>();
    CompletableFuture<String> withChain = new CompletableFuture<>();

    CompletableFuture.runAsync(() -> {
        String result1 = <LONG-DB-QUERY>;
        if (result1 == null) {
            shortCut.complete(internalServerError());
            return;
        }

        if (result1.equals("<SOME VALUE>")) {
            shortCut.complete(ok(param1));
            return;
        }

        withChain.complete(result1);
    });

    return withChain
            .thenCombine(CompletableFuture.supplyAsync(() -> <LONG-DB-QUERY>), (newParam1, newParam2) -> ok(result1+result2))
            .applyToEither(shortCut, Function.identity());
}