问题
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