CompletionStage

Doug Lea dl at cs.oswego.edu
Mon Jul 1 05:45:51 PDT 2013


On 06/30/13 20:24, Sam Pullara wrote:

> Experimenting a bit with the API to see if I could use it for cancellation, here
> is a program that I would like to work much differently than it does with the
> current system:
>
>      @Test
>      public void testCancellation() throws ExecutionException,
> InterruptedException {
>          AtomicBoolean cancelled = new AtomicBoolean();
>          AtomicBoolean handled = new AtomicBoolean();
>          AtomicBoolean handleCalledWithValue = new AtomicBoolean();
>          CompletableFuture<String> other = supplyAsync(() -> "Doomed value");
>          CompletableFuture<String> future = supplyAsync(() -> {
>              sleep(1000);
>              return "Doomed value";
>          }).exceptionally(t -> {
>              cancelled.set(true);
>              return null;
>          }).thenCombine(other, (a, b) -> a + ", " + b).handle((v, t) -> {
>              if (t == null) {
>                  handleCalledWithValue.set(true);
>              }
>              handled.set(true);
>              return null;
>          });
>          sleep(100);
>          future.cancel(true);
>          sleep(1000);
>          try {
>              future.get();
>              fail("Should have thrown");
>          } catch (CancellationException ce) {
>              System.out.println("future cancelled: " + future.isCancelled());
>              System.out.println("other cancelled: " + other.isCancelled());
>              System.out.println("exceptionally called: " + cancelled.get());
>              System.out.println("handle called: " + handled.get());
>              System.out.println("handle called with value: " +
> handleCalledWithValue.get());
>          }
>      }
>

I think that variable "future" is not bound to the stage you have in mind?
(The joys of fluency...)

Try it with:
         ...
         CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
                 sleep(1000);
                 return "Doomed value";
             });
         future.cancel(true);
         future.exceptionally(...

         // or, as of now, you could do instead
         future.onExceptionalCompletion(t -> {
          ...

-Doug





More information about the lambda-libs-spec-experts mailing list