【问题标题】:CompletableFuture return totally different futureCompletableFuture 返回完全不同的未来
【发布时间】:2015-05-16 05:35:06
【问题描述】:

我正在研究 Java 8 CompletableFuture(在 Scala 或 JS 等语言中的 Promise)。

可能是我做错了什么或者没有找到任何描述。设置几个回调后返回的未来返回完全独立的未来。

我对此进行了一些单元测试:

public class FutureTest {
    private boolean stage1;
    private boolean stage2;

    @Before
    public void setUp() throws Exception {
        this.stage1 = false;
        this.stage2 = false;
    }

    @Test
    public void testCombinationOfCallbacks() throws Exception {
        final CompletableFuture<String> future = new CompletableFuture<>();

        future
            .whenComplete((s, e) -> stage1 = true)
            .whenComplete((s, e) -> stage2 = true);

        future.complete("done");

        assertTrue(stage1);
        assertTrue(stage2);
        assertEquals("done", future.get());
    }

    @Test
    public void testCombinationOfCallbacksCalledOnReturnedFuture() throws Exception {
        final CompletableFuture<String> future = new CompletableFuture<>();

        final CompletableFuture<String> returnedFuture = future
                .whenComplete((s, e) -> stage1 = true)
                .whenComplete((s, e) -> stage2 = true);

        returnedFuture.complete("done");

        assertFalse(future.isDone());
        assertFalse(stage1);
        assertFalse(stage2);
    }
}

正如您在第二个测试中看到的那样,最初创建的未来不受通过回调完成未来的事实的影响。所以基本上回调是在创建的未来上设置的,但不返回未来。

表示你从来没有做过这样的事情:

private CompletableFuture<String> createFuture() {
    return new CompletableFuture<String>()
        .whenComplete((s, e) -> stage1 = true)
        .whenComplete((s, e) -> stage2 = true);
}

它是否记录在 JavaDocs 的某个地方?

【问题讨论】:

    标签: java-8 future


    【解决方案1】:

    javadocs 说的是方法可以做什么,而不是他们不能做的无数其他事情:

        public CompletionStage<T> whenComplete
        (BiConsumer<? super T, ? super Throwable> action);
    

    返回具有相同结果或异常的 CompletionStage
    作为这个阶段,当这个阶段完成时,执行
    给定带有结果的操作(如果没有,则为 {@code null})和
    此阶段的异常(或 {@code null},如果没有)。

    @param action 要执行的操作
    @return 新的 CompletionStage

    文档说您在每次调用whenComplete 时创建一个新的CompletionStageCompleteableFuture 实现),他们只提到从旧阶段到新阶段的结果前向传播。

    您只能假设这些方法执行文档描述的操作。

    您所期望的是从新阶段到旧阶段的反向传播,这显然 在 javadocs 的任何地方都没有提及,因此您不应该首先期待这种行为.

    【讨论】:

      猜你喜欢
      • 2019-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2020-03-06
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      相关资源
      最近更新 更多