Class AsyncUtil
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.
-
Method Summary
Modifier and TypeMethodDescriptionstatic <T,R> void asyncApply(ApplyFunction<T, R> function) Applies an asynchronous function to the currentCompletableFuture.static <T,R> void asyncApplyUseExecutor(ApplyFunction<T, R> function, Executor executor) Applies an asynchronous function to the currentCompletableFutureusing the specified executor.static <R,E extends Throwable>
voidasyncCatch(CatchFunction<R, E> function, Class<E> eClass) Handles exceptions to a specified type that may occur during an asynchronous operation.static <R> voidasyncComplete(R value) Completes the current asynchronous operation with the specified value.static <R> voidasyncCompleteWith(CompletableFuture<R> completableFuture) Completes the current asynchronous operation with the specified completableFuture.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.static <R> voidasyncFinally(FinallyFunction<R> function) Executes a final action after an asynchronous operation completes, regardless of whether the operation was successful or resulted in an exception.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.static <R> RasyncReturn(Class<R> clazz) Provides a default value based on the type specified.static voidCompletes the current asynchronous operation with an exception.static <R> voidAttempts to execute an asynchronous task defined by the providedAsyncRunand associates it with the current thread'sCompletableFuture.static CompletableFuture<Object>static CompletableFuture<Object>Get the CompletableFuture object stored in the current thread's local variable.static <R> RsyncReturn(Class<R> clazz) Synchronously returns the result of the current asynchronous operation.
-
Method Details
-
asyncReturn
Provides a default value based on the type specified. -
syncReturn
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
CompletableFutureand 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 anExecutionException.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- theClassobject 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'sCompletableFutureto 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
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
-
asyncThrowException
Completes the current asynchronous operation with an exception. This method sets the result of the current thread'sCompletableFutureto an exceptional completion, using the providedThrowableas the cause. This is typically used to handle errors in asynchronous operations.- Parameters:
e- The exception to complete the future exceptionally with.
-
asyncApply
Applies an asynchronous function to the currentCompletableFuture. This method retrieves the current thread'sCompletableFutureand applies the providedApplyFunctionto 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
Applies an asynchronous function to the currentCompletableFutureusing the specified executor. This method retrieves the current thread'sCompletableFutureand applies the providedApplyFunctionto 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
Attempts to execute an asynchronous task defined by the providedAsyncRunand associates it with the current thread'sCompletableFuture. This method is useful for trying operations that may throw exceptions and handling them asynchronously.The provided
asyncRunis 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 anAsyncRuninstance.- 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
functionis aCatchFunctionthat 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
eClassparameter 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- TheCatchFunctionthat defines how to handle the caught exception.eClass- The class of the exception type to catch.- See Also:
-
asyncFinally
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
functionis aFinallyFunctionthat 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- TheFinallyFunctionthat 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
asyncDois anAsyncBiFunctionthat 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 overR- 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 functionasyncDo- the asynchronous function to apply to each element of the Iterator, implemented as anAsyncBiFunction- See Also:
-
asyncCurrent
public static <I,R, void asyncCurrentP> (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
asyncDois applied to each element of the collection. This operation is expected to return aCompletableFuturerepresenting the asynchronous task. Once all tasks have been started, the method (async) waits for all of them to complete and then uses thethenfunction to process and aggregate the results.The
thenfunction takes an array ofCompletableFutureinstances, 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 aCompletableFuturerepresenting 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
Get the CompletableFuture object stored in the current thread's local variable.- Returns:
- The completableFuture object.
-