Last active
April 4, 2018 06:28
-
-
Save adamw/c62cb0c08fcbbb3892bc9718f77ab2d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package test; | |
| import java.util.List; | |
| import java.util.concurrent.CompletableFuture; | |
| import java.util.stream.Collectors; | |
| public class Compare3aWrappers { | |
| // data structures | |
| class RSS { | |
| String getFeedAddress() { return null; } | |
| } | |
| // I/O operations: non-blocking, asynchronous | |
| <T> CompletableFuture<T> fetchFromDb(Class<T> entityClass, long id) { return null; } | |
| CompletableFuture<String> sendHttpGet(String url) { return null; } | |
| // the business logic: asynchronous | |
| CompletableFuture<List<String>> fetchRssContent(List<Long> rssIds) | |
| throws InterruptedException { | |
| List<CompletableFuture<String>> listOfFutureContents = | |
| rssIds.stream() | |
| // all I/O db operations will run concurrently | |
| .map(rssId -> fetchFromDb(RSS.class, rssId)) | |
| // after each db operation is complete, | |
| // scheduling the http send | |
| .map(futureRss -> futureRss.thenCompose(rss -> | |
| sendHttpGet(rss.getFeedAddress()))) | |
| .collect(Collectors.toList()); | |
| // combining a list of futures into a future of a list | |
| return CompletableFuture.allOf(listOfFutureContents.toArray( | |
| new CompletableFuture[0])) | |
| .thenApply(v -> listOfFutureContents.stream() | |
| // we are now certain all futures are done | |
| .map(CompletableFuture::join) | |
| .collect(Collectors.toList())); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment