java.lang.Object
org.apache.hadoop.hdfs.server.federation.router.async.utils.AsyncUtil

public final class AsyncUtil extends Object
The AsyncUtil class provides a collection of utility methods to simplify the implementation of asynchronous operations using Java's CompletableFuture. It encapsulates common patterns such as applying functions, handling exceptions, and executing tasks in a non-blocking manner. This class is designed to work with Hadoop's asynchronous router operations in HDFS Federation.

The utility methods support a fluent-style API, allowing for the chaining of asynchronous operations. For example, after an asynchronous operation completes, a function can be applied to its result, and the process can continue with the new result. This is particularly useful for complex workflows that require multiple steps, where each step depends on the completion of the previous one.

The class also provides methods to handle exceptions that may occur during a synchronous operation. This ensures that error handling is integrated smoothly into the workflow, allowing for robust and fault-tolerant applications.

See Also:
  • Method Details

    • asyncReturn

      public static <R> R asyncReturn(Class<R> clazz)
      Provides a default value based on the type specified.
      Type Parameters:
      R - The type of the value to be returned.
      Parameters:
      clazz - The Class object representing the type of the value to be returned.
      Returns:
      An object with a value determined by the type:
      • false if clazz is Boolean,
      • -1 if clazz is Long,
      • -1 if clazz is Integer,
      • null for any other type.
    • syncReturn

      public static <R> R syncReturn(Class<R> clazz) throws Exception
      Synchronously returns the result of the current asynchronous operation. This method is designed to be used in scenarios where the result of an asynchronous operation is needed synchronously, and it is known that the operation has completed.

      The method retrieves the current thread's CompletableFuture and attempts to get the result. If the future is not yet complete, this method will block until the result is available. If the future completed exceptionally, the cause of the exception is thrown as a runtime exception wrapped in an ExecutionException.

      This method is typically used after an asynchronous operation has been initiated and the caller needs to obtain the result in a synchronous manner, for example, when bridging between asynchronous and synchronous code paths.

      Type Parameters:
      R - the type of the result to be returned
      Parameters:
      clazz - the Class object representing the type of the value to be returned, used to cast the result to the correct type
      Returns:
      the result of the asynchronous operation as an object of the specified class
      Throws:
      Exception - if an error occurs during the synchronous retrieval of the result, including the original exception if the future completed exceptionally
    • asyncComplete

      public static <R> void asyncComplete(R value)
      Completes the current asynchronous operation with the specified value. This method sets the result of the current thread's CompletableFuture to the provided value, effectively completing the asynchronous operation.
      Type Parameters:
      R - The type of the value to be completed.
      Parameters:
      value - The value to complete the future with.
    • asyncCompleteWith

      public static <R> void asyncCompleteWith(CompletableFuture<R> completableFuture)
      Completes the current asynchronous operation with the specified completableFuture.
      Type Parameters:
      R - The type of the value to be completed.
      Parameters:
      completableFuture - The completableFuture to complete the future with.
    • getAsyncUtilCompletableFuture

      public static CompletableFuture<Object> getAsyncUtilCompletableFuture()
    • asyncThrowException

      public static void asyncThrowException(Throwable e)
      Completes the current asynchronous operation with an exception. This method sets the result of the current thread's CompletableFuture to an exceptional completion, using the provided Throwable as the cause. This is typically used to handle errors in asynchronous operations.
      Parameters:
      e - The exception to complete the future exceptionally with.
    • asyncApply

      public static <T, R> void asyncApply(ApplyFunction<T,R> function)
      Applies an asynchronous function to the current CompletableFuture. This method retrieves the current thread's CompletableFuture and applies the provided ApplyFunction to it. It is used to chain asynchronous operations, where the result of one operation is used as the input for the next.
      Type Parameters:
      T - The type of the input to the function.
      R - The type of the result of the function.
      Parameters:
      function - The asynchronous function to apply, which takes a type T and produces a type R.
      See Also:
    • asyncApplyUseExecutor

      public static <T, R> void asyncApplyUseExecutor(ApplyFunction<T,R> function, Executor executor)
      Applies an asynchronous function to the current CompletableFuture using the specified executor. This method retrieves the current thread's CompletableFuture and applies the providedApplyFunction to it with the given executor service. It allows for more control over the execution context, such as running the operation in a separate thread or thread pool.

      This is particularly useful when you need to perform blocking I/O operations or other long-running tasks without blocking the main thread or when you want to manage the thread resources more efficiently.

      Type Parameters:
      T - The type of the input to the function.
      R - The type of the result of the function.
      Parameters:
      function - The asynchronous function to apply, which takes a type T and produces a type R.
      executor - The executor service used to run the asynchronous function.
      See Also:
    • asyncTry

      public static <R> void asyncTry(AsyncRun<R> asyncRun)
      Attempts to execute an asynchronous task defined by the provided AsyncRun and associates it with the current thread's CompletableFuture. This method is useful for trying operations that may throw exceptions and handling them asynchronously.

      The provided asyncRun is a functional interface that encapsulates the logic to be executed asynchronously. It is executed in the context of the current CompletableFuture, allowing for chaining further asynchronous operations based on the result or exception of this try.

      If the operation completes successfully, the result is propagated to the next operation in the chain. If an exception occurs, it can be caught and handled using the asyncCatch(CatchFunction, Class) method, allowing for error recovery or alternative processing.

      Type Parameters:
      R - The type of the result produced by the asynchronous task.
      Parameters:
      asyncRun - The asynchronous task to be executed, defined by an AsyncRun instance.
      See Also:
    • asyncCatch

      public static <R, E extends Throwable> void asyncCatch(CatchFunction<R,E> function, Class<E> eClass)
      Handles exceptions to a specified type that may occur during an asynchronous operation. This method is used to catch and deal with exceptions in a non-blocking manner, allowing the application to continue processing even when errors occur.

      The provided function is a CatchFunction that defines how to handle the caught exception. It takes the result of the asynchronous operation (if any) and the caught exception, and returns a new result or modified result to continue the asynchronous processing.

      The eClass parameter specifies the type of exceptions to catch. Only exceptions that are instances of this type (or its subclasses) will be caught and handled by the provided function.

      Type Parameters:
      R - The type of the result of the asynchronous operation.
      E - The type of the exception to catch.
      Parameters:
      function - The CatchFunction that defines how to handle the caught exception.
      eClass - The class of the exception type to catch.
      See Also:
    • asyncFinally

      public static <R> void asyncFinally(FinallyFunction<R> function)
      Executes a final action after an asynchronous operation completes, regardless of whether the operation was successful or resulted in an exception. This method provides a way to perform cleanup or finalization tasks in an asynchronous workflow.

      The provided function is a FinallyFunction that encapsulates the logic to be executed after the asynchronous operation. It takes the result of the operation and returns a new result, which can be used to continue the asynchronous processing or to handle the final output of the workflow.

      This method is particularly useful for releasing resources, closing connections, or performing other cleanup actions that need to occur after all other operations have completed.

      Type Parameters:
      R - The type of the result of the asynchronous operation.
      Parameters:
      function - The FinallyFunction that defines the final action to be executed.
      See Also:
    • asyncForEach

      public static <I, R> void asyncForEach(Iterator<I> forEach, AsyncBiFunction<AsyncForEachRun<I,R>,I,R> asyncDo)
      Executes an asynchronous operation for each element in an Iterator, applying a given async function to each element. This method is part of the asynchronous utilities provided to facilitate non-blocking operations on collections of elements.

      The provided asyncDo is an AsyncBiFunction that encapsulates the logic to be executed asynchronously for each element. It is executed in the context of the current CompletableFuture, allowing for chaining further asynchronous operations based on the result or exception of each iteration.

      The method is particularly useful for performing asynchronous iterations over collections where the processing of each element is independent.

      Type Parameters:
      I - the type of the elements being iterated over
      R - the type of the result produced by the asynchronous task applied to each element
      Parameters:
      forEach - the Iterator over which to iterate and apply the async function
      asyncDo - the asynchronous function to apply to each element of the Iterator, implemented as an AsyncBiFunction
      See Also:
    • asyncCurrent

      public static <I, R, P> void asyncCurrent(Collection<I> collection, AsyncApplyFunction<I,R> asyncDo, Function<CompletableFuture<R>[],P> then)
      Applies an asynchronous operation to each element of a collection and aggregates the results. This method is designed to process a collection of elements concurrently using asynchronous tasks, and then combine the results into a single aggregated result.

      The operation defined by asyncDo is applied to each element of the collection. This operation is expected to return a CompletableFuture representing the asynchronous task. Once all tasks have been started, the method (async) waits for all of them to complete and then uses the then function to process and aggregate the results.

      The then function takes an array of CompletableFuture instances, each representing the future result of an individual asynchronous operation. It should return a new aggregated result based on these futures. This allows for various forms of result aggregation, such as collecting all results into a list, reducing them to a single value, or performing any other custom aggregation logic.

      Type Parameters:
      I - the type of the elements in the collection.
      R - the type of the intermediate result from the asynchronous operations.
      P - the type of the final aggregated result.
      Parameters:
      collection - the collection of elements to process.
      asyncDo - the asynchronous operation to apply to each element. It must return a CompletableFuture representing the operation.
      then - a function that takes an array of futures representing the results of the asynchronous operations and returns an aggregated result.
      See Also:
    • getCompletableFuture

      public static CompletableFuture<Object> getCompletableFuture()
      Get the CompletableFuture object stored in the current thread's local variable.
      Returns:
      The completableFuture object.