Class CompletableFutureUtils

java.lang.Object
dev.langchain4j.internal.CompletableFutureUtils

public class CompletableFutureUtils extends Object
Utility methods for working with CompletableFuture.
  • Method Details

    • propagateCancellation

      public static void propagateCancellation(CompletableFuture<?> from, CompletableFuture<?> to)
      Forwards cancellation from one future to another.

      CompletableFuture.cancel(boolean) does not propagate to the stages a future was derived from, so when from represents the future handed to a caller and to represents the underlying work (e.g. an in-flight HTTP request), cancelling from would otherwise leave to running. This method bridges that gap: once from completes, if it was cancelled, to is cancelled too.

      Parameters:
      from - the future whose cancellation should be propagated; ignored if null.
      to - the future to cancel when from is cancelled.
    • failOnThrow

      public static <T> CompletableFuture<T> failOnThrow(Supplier<CompletableFuture<T>> operation)
      Calls an asynchronous operation so that the caller never sees it throw, which is the rule for every method that returns a CompletableFuture: anything the operation throws, including an Error, is returned as a failed future, and a null future as a future failed with an IllegalStateException.

      Use failOnThrow(Object, String, Supplier) when the operation can return null, so that the message names the method that did.

      Parameters:
      operation - the operation that returns the future
      Returns:
      the future returned by the operation, or a failed future
    • failOnThrow

      public static <T> CompletableFuture<T> failOnThrow(Object target, String method, Supplier<CompletableFuture<T>> operation)
      Like failOnThrow(Supplier), but a null future fails with an IllegalStateException that names the method that returned it: the class name of target, then method, for example "<class name of target>.doChatAsync(ChatRequest) returned null".
      Parameters:
      target - the object whose method the operation calls
      method - the method the operation calls, for example "doChatAsync(ChatRequest)"
      operation - the operation that returns the future
      Returns:
      the future returned by the operation, or a failed future