如何将1个可完成的未来分成流中的许多可完成的未来?

时间:2016-09-30 13:06:47

标签: java java-8 java-stream completable-future

例如我有这样的方法:

public CompletableFuture<Page> getPage(int i) {
    ...
}
public CompletableFuture<Document> getDocument(int i) {
    ...
}
public CompletableFuture<Void> parseLinks(Document doc) {
    ...
}

我的流程:

List<CompletableFuture> list = IntStream
    .range(0, 10)
    .mapToObj(i -> getPage(i))

    // I want method like this:
    .thenApplyAndSplit(CompletableFuture<Page> page -> {
        List<CompletableFuture<Document>> docs = page.getDocsId()
            .stream()
            .map(i -> getDocument(i))
            .collect(Collectors.toList());
        return docs;
    })
    .map(CompletableFuture<Document> future -> {
        return future.thenApply(Document doc -> parseLink(doc);
    })
    .collect(Collectors.toList());

对于flatMap()来说应该是CompletableFuture之类的东西,所以我想实现这个流程:

List<Integer> -> Stream<CompletableFuture<Page>>
              -> Stream<CompletableFuture<Document>>
              -> parse each

更新

Stream<CompletableFuture<Page>> pagesCFS = IntStream
        .range(0, 10)
        .mapToObj(i -> getPage(i));

Stream<CompletableFuture<Document>> documentCFS = listCFS.flatMap(page -> {
    // How to return stream of Document when page finishes?
    // page.thenApply( ... )
})

3 个答案:

答案 0 :(得分:2)

我还想尝试为Spliterator的流实施CompletableFutures,所以这是我的尝试。

请注意,如果您在 parallel 模式下使用此功能,请注意为流使用不同的ForkJoinPool以及在CompletableFuture后面运行的任务秒。流将等待期货完成,因此如果它们共享相同的执行程序,甚至遇到死锁,您实际上可能会失去性能。

所以这是实施:

public static <T> Stream<T> flattenStreamOfFutures(Stream<CompletableFuture<? extends T>> stream, boolean parallel) {
    return StreamSupport.stream(new CompletableFutureSpliterator<T>(stream), parallel);
}

public static <T> Stream<T> flattenStreamOfFuturesOfStream(Stream<CompletableFuture<? extends Stream<T>>> stream,
                                                           boolean parallel) {
    return flattenStreamOfFutures(stream, parallel).flatMap(Function.identity());
}

public static class CompletableFutureSpliterator<T> implements Spliterator<T> {
    private List<CompletableFuture<? extends T>> futures;

    CompletableFutureSpliterator(Stream<CompletableFuture<? extends T>> stream) {
        futures = stream.collect(Collectors.toList());
    }

    CompletableFutureSpliterator(CompletableFuture<T>[] futures) {
        this.futures = new ArrayList<>(Arrays.asList(futures));
    }

    CompletableFutureSpliterator(final List<CompletableFuture<? extends T>> futures) {
        this.futures = new ArrayList<>(futures);
    }

    @Override
    public boolean tryAdvance(final Consumer<? super T> action) {
        if (futures.isEmpty())
            return false;
        CompletableFuture.anyOf(futures.stream().toArray(CompletableFuture[]::new)).join();
        // now at least one of the futures has finished, get its value and remove it
        ListIterator<CompletableFuture<? extends T>> it = futures.listIterator(futures.size());
        while (it.hasPrevious()) {
            final CompletableFuture<? extends T> future = it.previous();
            if (future.isDone()) {
                it.remove();
                action.accept(future.join());
                return true;
            }
        }
        throw new IllegalStateException("Should not reach here");
    }

    @Override
    public Spliterator<T> trySplit() {
        if (futures.size() > 1) {
            int middle = futures.size() >>> 1;
            // relies on the constructor copying the list, as it gets modified in place
            Spliterator<T> result = new CompletableFutureSpliterator<>(futures.subList(0, middle));
            futures = futures.subList(middle, futures.size());
            return result;
        }
        return null;
    }

    @Override
    public long estimateSize() {
        return futures.size();
    }

    @Override
    public int characteristics() {
        return IMMUTABLE | SIZED | SUBSIZED;
    }
}

它的工作原理是将给定的Stream<CompletableFuture<T>>转换为这些未来的List - 假设构建流是快速的,艰苦的工作由期货本身完成,因此列出一个列表它不应该是昂贵的。这也确保所有任务都已被触发,因为它强制处理源流。

为了生成输出流,它只是在流式传输其值之前等待任何未来完成。

一个简单的非并行用法示例(执行程序用于CompletableFuture,以便同时启动它们):

ExecutorService executor = Executors.newFixedThreadPool(20);
long start = System.currentTimeMillis();
flattenStreamOfFutures(IntStream.range(0, 20)
        .mapToObj(i -> CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep((i % 10) * 1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            System.out.println("Finished " + i + " @ " + (System.currentTimeMillis() - start) + "ms");
            return i;
        }, executor)), false)
        .forEach(x -> {
            System.out.println(Thread.currentThread().getName() + " @ " + (System.currentTimeMillis() - start) + "ms handle result: " + x);
        });
executor.shutdown();

输出:

Finished 10 @ 103ms
Finished 0 @ 105ms
main @ 114ms handle result: 10
main @ 114ms handle result: 0
Finished 1 @ 1102ms
main @ 1102ms handle result: 1
Finished 11 @ 1104ms
main @ 1104ms handle result: 11
Finished 2 @ 2102ms
main @ 2102ms handle result: 2
Finished 12 @ 2104ms
main @ 2105ms handle result: 12
Finished 3 @ 3102ms
main @ 3102ms handle result: 3
Finished 13 @ 3104ms
main @ 3105ms handle result: 13
…

正如您所看到的,即使期货没有按顺序完成,流也会立即产生价值。

将其应用于问题中的示例,这会给出(假设parseLinks()返回CompletableFuture<String>而不是~<Void>):

flattenStreamOfFuturesOfStream(IntStream.range(0, 10)
                .mapToObj(this::getPage)
                // the next map() will give a Stream<CompletableFuture<Stream<String>>>
                // hence the need for flattenStreamOfFuturesOfStream()
                .map(pcf -> pcf
                        .thenApply(page -> flattenStreamOfFutures(page
                                        .getDocsId()
                                        .stream()
                                        .map(this::getDocument)
                                        .map(docCF -> docCF.thenCompose(this::parseLinks)),
                                false))),
        false)
.forEach(System.out::println);

答案 1 :(得分:0)

你真的必须使用Streams吗?你不能只为你的CompletableFutures做一些依赖行动吗?特别是因为您的上一次通话返回CompletableFutures<Void>(当然,也可以使用Collection.forEach

List<CompletableFuture<Page>> completableFutures = IntStream
      .range(0, 10)
      .mapToObj(i -> getPage(i)).collect(Collectors.toList());

for (CompletableFuture<Page> page : completableFutures) {
    page.thenAccept(p -> {
        List<Integer> docsId = p.getDocsId();
        for (Integer integer : docsId) {
            getDocument(integer).thenAccept(d-> parseLinks(d));
        }
    });
}

编辑:那么我做了另一次尝试,但我不确定这是不是一个好主意,因为我不是CompletableFuture的专家。

使用以下方法(可能有更好的实现):

public static <T> CompletableFuture<Stream<T>> flatMapCF(Stream<CompletableFuture<T>> stream){
    return CompletableFuture.supplyAsync( ()->
        stream.map(CompletableFuture::join)
    );
}


Stream<CompletableFuture<Page>> pagesCFS = IntStream
        .range(0, 10)
        .mapToObj(i -> getPage(i));

CompletableFuture<Stream<Page>> pageCF = flatMapCF(pagesCFS);

CompletableFuture<Stream<Document>> docCF= 
   pageCF.thenCompose(a ->
        flatMapCF(a.flatMap(
                b -> b.getDocsId()
                        .stream()
                        .map(c -> getDocument(c))
        )));

问题可能是CompletableFuture仅在所有结果都可用时返回

答案 2 :(得分:0)

如果您不关心操作何时完成,那么以下内容只会在所有文档上触发parseLinks()

IntStream.range(0, 10)
        .mapToObj(this::getPage)
        .forEach(pcf -> pcf
                .thenAccept(page -> page
                        .getDocsId()
                        .stream()
                        .map(this::getDocument)
                        .forEach(docCF -> docCF.thenCompose(this::parseLinks))));

否则,当您的上一个操作返回CompletableFuture<Void>时,我认为您将主要知道什么时候完成所有操作。你可以这样做:

CompletableFuture<Void> result = CompletableFuture.allOf(IntStream.range(0, 10)
        .mapToObj(this::getPage)
        .map(pcf -> pcf
                .thenCompose(page -> CompletableFuture.allOf(page
                        .getDocsId()
                        .stream()
                        .map(docId -> getDocument(docId)
                                .thenCompose(this::parseLinks))
                        .toArray(CompletableFuture[]::new))))
        .toArray(CompletableFuture[]::new));

如果您对单个CompletableFuture的结果感兴趣,最好的方法是直接在流中,在它们创建的位置处理它们。

你甚至可以用可重复使用的方法将它们全部包装起来。例如,如果parseLinks()返回CompletableFuture<List<String>>,您可以定义如下方法:

public CompletableFuture<Void> processLinks(Function<? super CompletableFuture<List<String>>, ? extends CompletableFuture<?>> processor) {
    return CompletableFuture.allOf(IntStream.range(0, 10)
            .mapToObj(this::getPage)
            .map(pcf -> pcf
                    .thenCompose(page -> CompletableFuture.allOf(page
                            .getDocsId()
                            .stream()
                            .map(docId -> getDocument(docId)
                                    .thenCompose(this::parseLinks))
                            .map(processor) // here we apply the received function
                            .toArray(CompletableFuture[]::new))))
            .toArray(CompletableFuture[]::new));
}

并像这样处理结果列表:

processLinks(linksCF -> linksCF
        .thenAccept(links -> links.forEach(System.out::println)));

一旦打印完所有链接,返回的CompletableFuture就会完成。

相关问题