Created
April 29, 2016 03:28
-
-
Save parambirs/71ab4bfd65b1900f4d4261e896b4def0 to your computer and use it in GitHub Desktop.
An example of composing CompletableFutures where the underlying future can fail.
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
| import java.time.Duration; | |
| import java.time.temporal.ChronoUnit; | |
| import java.util.concurrent.CompletableFuture; | |
| import static java.lang.System.err; | |
| import static java.lang.System.out; | |
| public class HelloCompletableFuturesWithFailures { | |
| public static void main(String[] args) { | |
| CompletableFuture<String> future = new Async().thinkOfSomething(); | |
| future.thenApply(String::toUpperCase) | |
| .handle((ok, ex) -> { | |
| if (ok != null) { | |
| out.println(ok); | |
| return ok; | |
| } else { | |
| err.println("Got an exception: " + ex.getMessage()); | |
| return null; | |
| } | |
| }); | |
| } | |
| } | |
| class Async { | |
| CompletableFuture<String> thinkOfSomething() { | |
| CompletableFuture<String> future = new CompletableFuture<>(); | |
| new Thread(new Task(future)).start(); | |
| return future; | |
| } | |
| private class Task implements Runnable { | |
| private final CompletableFuture<String> future; | |
| Task(CompletableFuture<String> future) { | |
| this.future = future; | |
| } | |
| public void run() { | |
| try { | |
| Thread.sleep(Duration.of(3, ChronoUnit.SECONDS).toMillis()); | |
| future.completeExceptionally(new RuntimeException("The future is bleak...")); | |
| } catch (InterruptedException e) { | |
| future.completeExceptionally(e); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment