Class CompletableFutureCancellationHandler

java.lang.Object
org.apache.pulsar.common.util.CompletableFutureCancellationHandler

public class CompletableFutureCancellationHandler extends Object
Implements cancellation and timeout support for CompletableFutures.

This class ensures that the cancel action gets called once after the future completes with either CancellationException or TimeoutException. The implementation handles possible race conditions that might happen when the future gets cancelled before the cancel action is set to this handler.

For timeouts, CompletableFuture's "orTimeout" method introduced in JDK9 can be used in client code.

Cancellation and timeout support will only be active on the future where the cancellation handler has been attached to. Cancellation won't happen if .cancel is called on any "downstream" dependent futures. A cancellation or timeout that happens in any "upstream" future will get handled.

  • Constructor Details

    • CompletableFutureCancellationHandler

      public CompletableFutureCancellationHandler()
  • Method Details

    • createFuture

      public <T> CompletableFuture<T> createFuture()
      Creates a new CompletableFuture and attaches the cancellation handler to handle cancels and timeouts.
      Type Parameters:
      T - the result type of the future
      Returns:
      a new future instance
    • attachToFuture

      public void attachToFuture(CompletableFuture<?> future)
      Attaches the cancellation handler to handle cancels and timeouts. A cancellation handler instance can be used only once.
      Parameters:
      future - the future to attach the handler to
    • setCancelAction

      public void setCancelAction(Runnable cancelAction)
      Set the action to run when the future gets cancelled or timeouts. The cancellation or timeout might be originating from any "upstream" future. The implementation ensures that the cancel action gets called once. Handles possible race conditions that might happen when the future gets cancelled before the cancel action is set to this handler. In this case, the cancel action gets called when the action is set.
      Parameters:
      cancelAction - the action to run when the the future gets cancelled or timeouts