Как ждать полного завершения завершаемого будущего с помощью runAsync? - PullRequest
0 голосов
/ 21 октября 2019

Этот тест не пройден:

package com.stackoverflow.demo;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ForkJoinPool;

import org.junit.Assert;
import org.junit.Test;

public class AsyncTest {

    @Test
    public void test1() {
        Assert.assertTrue("please run this test in a machine with 2 or more cores", ForkJoinPool.getCommonPoolParallelism() > 1);

        CompletableFuture<String> cf = CompletableFuture.completedFuture("ok");
        ConcurrentLinkedQueue<String> out = new ConcurrentLinkedQueue<>();

        cf.thenRunAsync(() -> {
            out.add("one");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            out.add("two");
        }, ForkJoinPool.commonPool());

        cf.join();

        Assert.assertEquals(2, out.size());
    }

}

Я был удивлен, потому что ожидал, что cf.join() примет во внимание все приложенные задачи. Я уверен, что где-то в документации говорится, что join ожидает только первоначальное задание, но почему-то я пропустил его.

Как я могу получить желаемое поведение: Ожидание CompletableFuture и всесвязанные с ним подзадачи для завершения ?

1 Ответ

0 голосов
/ 21 октября 2019

Исправлено во время корректуры моего поста:

public class AsyncTest {

    @Test
    public void test1() {
        Assert.assertTrue("please run this test in a machine with 2 or more cores", ForkJoinPool.getCommonPoolParallelism() > 1);

        CompletableFuture<String> cf = CompletableFuture.completedFuture("ok");
        ConcurrentLinkedQueue<String> out = new ConcurrentLinkedQueue<>();

        CompletableFuture<Void> cf2 = cf.thenRunAsync(() -> {
            out.add("one");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            out.add("two");
        }, ForkJoinPool.commonPool());

        cf2.join();

        Assert.assertEquals(2, out.size());
    }

}
...