Skip to content

Instantly share code, notes, and snippets.

@ben-barbier
Last active May 29, 2016 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ben-barbier/00133fbae5b18d6cd2020a8e1e6e78e9 to your computer and use it in GitHub Desktop.
Save ben-barbier/00133fbae5b18d6cd2020a8e1e6e78e9 to your computer and use it in GitHub Desktop.
CompletableFuture example (like javascript promises)
public class ThreadTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<String> refs = new ArrayList<String>();
refs.add("AA907");
refs.add("H0704");
refs.add("FD123");
refs.add("DV067");
List<CompletableFuture<ProductPivot>> list = new ArrayList<CompletableFuture<ProductPivot>>();
for (String ref : refs) {
list.add(CompletableFuture.supplyAsync(new Supplier<ProductPivot>() {
@Override
public ProductPivot get() {
RestTemplate template = new RestTemplate();
ResponseEntity<ProductPivot> product = template.getForEntity("http://myServer/v1/styles/" + ref, ProductPivot.class);
System.out.println("wake up !" + Thread.currentThread().getId());
return product.getBody();
}
}));
}
for (ProductPivot completableFuture : all(list).get()) {
System.out.println(completableFuture.getTitle());
}
}
public static <T> CompletableFuture<List<T>> all(List<CompletableFuture<T>> futures) {
CompletableFuture[] cfs = futures.toArray(new CompletableFuture[futures.size()]);
return CompletableFuture.allOf(cfs)
.thenApply(v ->
futures.stream().
map(CompletableFuture::join).
collect(Collectors.toList())
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment