I have defined completableFuture.supplyAsync() inside foreach loop, so each entry(each asynchronous task) adding a list and I need to get final list(after all asynchronous task adding list)from completableFuture.supplyAsync().How to achieve this?
Code snippet:
unporcessedList.forEach(entry -> {
CompletableFuture<List<ChangeLog>> cf =
CompletableFuture.supplyAsync((Supplier<List<ChangeLog>>) () -> {
mongoDBHelper.processInMongo(entry, getObject(entry, map),entryList);
return entryList;
}, executor);
});
Non blocking version
General example:
List<String> entries = new ArrayList<>(2);
entries.add("first");
entries.add("second");
List<CompletableFuture<String>> completableFutures = entries.stream()
.map((entry) -> {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(new Random().nextInt(5000) + 500);
} catch (InterruptedException e) {
e.printStackTrace();
}
return entry.concat(String.valueOf(entry.length()));
}).thenApply((e) -> new StringBuilder(e).reverse().toString());
}
).collect(Collectors.toList());
CompletableFuture
.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]))
.thenApply((v) -> completableFutures.stream().map((cf) -> cf.join()))
.get()
.forEach(System.out::println);
Your case:
List<CompletableFuture<List<ChangeLog>>> completableFutures = unporcessedList.stream()
.map((entry) -> {
return CompletableFuture.supplyAsync((Supplier<List<ChangeLog>>) () -> {
mongoDBHelper.processInMongo(entry, getObject(entry, map), entryList);
return entryList;
}, executor);
}
).collect(Collectors.toList());
CompletableFuture
.allOf(completableFutures.toArray(new CompletableFuture[completableFutures.size()]))
.thenApply((v) -> completableFutures.stream().map((cf) -> cf.join()))
.get()
.forEach(System.out::println);
You can use the get() Method that will block your application until the future is completed. So use something like this:
// Block and get the result of the Future
Supplier<List<ChangeLog>> result = cf.get();
More examples are described here: https://www.callicoder.com/java-8-completablefuture-tutorial/
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.