Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8233050

CompletableFuture `whenComplete` and `thenApply` change exceptional result

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • 8
    • core-libs

      ADDITIONAL SYSTEM INFORMATION :
      The has been reproduced on openjdk-8u232-b09 on Windows 10, openjdk-11.0.3 on Ubuntu 18.04 and openjdk-11.0.2 on Windows 10.

      A DESCRIPTION OF THE PROBLEM :
      According to the documentation on CompletableFuture.whenComplete(), this method "Returns a new CompletionStage with the same result or exception as this stage". However, subsequent invocations of whenComplete() provide a different exception. It has been wrapped in a CompletionException.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      The following test case produces two different stack traces for each of the whenComplete invocations:

          @Test
          public void testWhenCompleteKeepExceptionalResultIntact() {
              RuntimeException expected = new RuntimeException("original");

              CompletableFuture<?> result = new CompletableFuture<>();
              result.whenComplete((r, e) -> System.out.println(e.toString()))
                     .whenComplete((r, e) -> System.out.println(e.toString()));
              result.completeExceptionally(expected);
          }

          @Test
          public void testThenApplyKeepExceptionalResultIntact() {
              RuntimeException expected = new RuntimeException("original");

              CompletableFuture<?> result = new CompletableFuture<>();
              result.thenApply(e -> e)
                     .whenComplete((r, e) -> System.out.println(e.toString()));
              result.completeExceptionally(expected);
          }

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      For the first testcase (with whenComplete):
      java.lang.RuntimeException: original
      java.lang.RuntimeException: original

      For the second test (with thenApply)
      java.lang.RuntimeException: original
      ACTUAL -
      For the first testcase (with whenComplete):
      java.lang.RuntimeException: original
      java.util.concurrent.CompletionException: java.lang.RuntimeException: original

      For the second test (with thenApply)
      java.util.concurrent.CompletionException: java.lang.RuntimeException: original

      FREQUENCY : always


            dl Doug Lea
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: