Why lambda inside map is not running?

*爱你&永不变心* 提交于 2020-11-28 08:57:47

问题


I am trying to learn concurrency and lambdas in java 8. But my code is not entering lambda block inside map.

List<Book> bookList = new ArrayList<Book>();
    isbnList
    .stream()
    .map(isbn -> (CompletableFuture.supplyAsync( () -> {
        try {
            List<String> pageContents = getUrlContents(webLink + isbn);
            return new Book(
                parseBookTitle(pageContents),
                isbn,
                parseRank(pageContents)
            );
        } catch (IOException ex) {
            return null;
        }
    })).thenApply(a -> bookList.add(a))
    );

While debugging, code is exiting at .map line and I m getting empty bookList. Sequential code for same is giving me correct result.


回答1:


A stream pipeline is lazy. Without a terminal operation, your stream pipeline is not even executed. Stream.map is an intermediate operation so it won't trigger pipeline execution.

Now you could add a forEach step with the lambda expression cf -> cf.join() for joining on your created CompletableFuture instances for your pipeline to be executed and wait for each of your async futures to complete. But doing this way will defeat the whole purpose of using asynchronous futures, because you're submitting them sequentially and waiting on the completion of each one before submitting the next one.

Better yet, you could convert your stream to a parallel stream, use map with your async lambda body directly by removing the CompletableFuture.supplyAsync part and collecting with collect for a similar effect without the extra clutter.

List<Book> bookList = isbnList.parallelStream()
    .map(isbn -> {
        try {
            List<String> pageContents = getUrlContents(webLink + isbn);
            return new Book(
                parseBookTitle(pageContents),
                isbn,
                parseRank(pageContents)
            );
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }).collect(Collectors.toList());

Further reading: Stream operations and pipelines in the stream API javadoc.



来源:https://stackoverflow.com/questions/40371809/why-lambda-inside-map-is-not-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!