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

CompletableFuture.whenComplete(handler) doesn't run handler after direct complete

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      Given the following code:

              CompletableFuture<?> f1 = new CompletableFuture<>();
              CompletableFuture<?> f2 = f1.whenComplete((r, x) -> System.out.println("hello"));

              f2.complete(null);
              f1.complete(null);

      "hello" is not printed after the completion of f1. The docs on CompletableFuture have nothing in them to suggest that once f2 has been directly completed that the function which links f1 to f2 will not be run. The docs say that the function will be run once f1 completes. I can appreciate that there may be a desire to leave CompletableFuture as is, but it would be good to at least cover this in the JavaDoc. Note that this behavior is not specific to whenComplete, it is just most egregious on methods like whenComplete which "feel" like they apply entirely to the source future (f1).

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      run the provided code

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      "hello"
      ACTUAL -
      no output

      ---------- BEGIN SOURCE ----------
              CompletableFuture<?> f1 = new CompletableFuture<>();
              CompletableFuture<?> f2 = f1.whenComplete((r, x) -> System.out.println("hello"));

              f2.complete(null);
              f1.complete(null);
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
              CompletableFuture<?> f1 = new CompletableFuture<>();
              CompletableFuture<?> f2 = f1.whenComplete((r, x) -> System.out.println("hello")).whenComplete((r, x) -> {});

              f2.complete(null);
              f1.complete(null);

      FREQUENCY : always


            vklang Viktor Klang
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Resolved: