Package com.dianxin.tori.base.concurrent
Interface FutureAction<T>
- Type Parameters:
T- The expected return type of this action.
public interface FutureAction<T>
Represents an asynchronous execution unit, heavily inspired by JDA's RestAction but
designed to be completely independent and powered natively by
CompletableFuture.
A FutureAction is lazy; it will not execute until an execution method
like queue(), submit(), or complete() is called.
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic classA wrapper class to safely hold either the success value or the thrown exception. -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> FutureAction<T> Creates a new FutureAction from a givenCallabletask, but Executor is IO.static <T> FutureAction<T> Creates a new FutureAction from a givenCallabletask.default @NotNull FutureAction<T> addCheck(@NotNull BooleanSupplier checks) Appends a new check to the existing ones using a logical AND (invalid input: '&'invalid input: '&').default <U,O> @NotNull FutureAction <O> and(@NotNull FutureAction<U> other, @NotNull BiFunction<? super T, ? super U, ? extends O> accumulator) Combines the result of this action with another action using an accumulator function.booleancancel(boolean mayInterruptIfRunning) static <E> @NotNull FutureAction<List<E>> collect(@NotNull FutureAction<? extends E>... actions) Sequences multiple actions to run sequentially (one after another).static <E> @NotNull FutureAction<List<E>> collectParallel(@NotNull FutureAction<? extends E>... actions) Dispatches multiple actions to run in parallel simultaneously.default Tcomplete()Blocks the current thread and executes the action synchronously.complete(boolean shouldQueue) Blocks the current thread and executes the action synchronously.Blocks the current thread to execute the action synchronously, with a maximum waiting time.static <T> FutureAction<T> completed(T value) Creates a FutureAction that is already completed with the given value.@NotNull FutureAction<T> deadline(long timestamp) Sets an absolute Unix timestamp deadline for this action.default @NotNull FutureAction<T> Delays the execution or completion of this action by a specified duration.<U> @NotNull FutureAction<U> flatMap(@NotNull Function<? super T, ? extends FutureAction<U>> mapper) Chains another asynchronous action to run after this one completes successfully.static <T> FutureAction<T> fromCompletableFuture(@NotNull CompletableFuture<T> future, @Nullable Executor executor) Creates a new FutureAction from a givenCompletableFuture.@Nullable BooleanSupplierbooleanbooleanisDone()<U> @NotNull FutureAction<U> Transforms the result of this action using the provided mapping function.default @NotNull CompletableFuture<FutureAction.Result<T>> Maps the output of this action into a safeFutureAction.Resultwrapper, which encapsulates either the success value or the thrown exception.onErrorFlatMap(@Nullable Predicate<? super Throwable> condition, @NotNull Function<? super Throwable, ? extends FutureAction<? extends T>> map) Conditionally handles an exception by returning an entirely new asynchronous fallback action.default FutureAction<T> onErrorMap(@NotNull Function<? super Throwable, ? extends T> map) Maps the exception thrown by this action into a default successful result.onErrorMap(@Nullable Predicate<? super Throwable> condition, @NotNull Function<? super Throwable, ? extends T> map) Conditionally maps the exception into a successful result.@NotNull FutureAction<T> onErrorReturn(T fallback) Directly returns a hardcoded fallback value if an exception occurs.@NotNull FutureAction<T> onExecutor(@NotNull Executor executor) Transfers the completion processing of this action to a specific executor.@NotNull FutureAction<T> Appends a failure callback without interrupting the chain.@NotNull FutureAction<T> Appends a success callback without interrupting the chain.default voidqueue()Submits the action for asynchronous execution.default voidSubmits the action for asynchronous execution with a specific success callback.voidSubmits the action for asynchronous execution with specific success and failure callbacks.default voidqueueAfter(long delay, @NotNull TimeUnit unit) default voidqueueAfter(long delay, @NotNull TimeUnit unit, @Nullable Consumer<? super T> success) default voidqueueAfter(long delay, @NotNull TimeUnit unit, @Nullable Consumer<? super T> success, @Nullable Consumer<? super Throwable> failure) Queues the action asynchronously after waiting for a specified delay.@NotNull FutureAction<T> Recovers from an exception by providing a fallback value.default @NotNull FutureAction<T> retryIfError(int retries) Retries this action immediately up to the specified maximum attempts if an error occurs.default @NotNull FutureAction<T> retryIfError(int retries, @NotNull Duration delay) Retries this action with a fixed backoff delay between attempts if an error occurs.default @NotNull FutureAction<T> retryIfError(int retries, @NotNull Duration delay, @Nullable Runnable onRetry) Retries this action with a fixed backoff delay and an execution hook invoked prior to each retry.default @NotNull FutureAction<T> retryIfError(int retries, @NotNull Duration delay, @Nullable Runnable onRetry, @Nullable Predicate<? super Throwable> condition) Retries this action using a comprehensive set of shortcut configurations including backoff, lifecycle hook, and error filtering.@NotNull FutureAction<T> Retries this action based on a custom retry strategy defined by aRetrypolicy.@NotNull FutureAction<T> setChecks(@Nullable BooleanSupplier checks) Sets a condition (check) that must returntruebefore the action is executed.default @NotNull CompletableFuture<T> submit()Submits the action for asynchronous execution and returns aCompletableFuture.@NotNull CompletableFuture<T> submit(boolean shouldQueue) Submits the action and returns aCompletableFuture.default @NotNull FutureAction<T> Sets a relative timeout for this action.default @NotNull FutureAction<List<T>> zip(@NotNull FutureAction<? extends T> first, @NotNull FutureAction<? extends T>... other) Zips the results of multiple actions together in parallel execution.
-
Method Details
-
action
Creates a new FutureAction from a givenCallabletask, but Executor is IO.- Type Parameters:
T- The return type of the task.- Parameters:
task- The task to be executed.- Returns:
- A new FutureAction instance.
-
action
@CheckReturnValue static <T> FutureAction<T> action(@NotNull @NotNull Callable<T> task, @Nullable @Nullable Executor executor) Creates a new FutureAction from a givenCallabletask.- Type Parameters:
T- The return type of the task.- Parameters:
task- The task to be executed.executor- The executor to run the task on. If null, falls back to the default IO executor.- Returns:
- A new FutureAction instance.
-
fromCompletableFuture
@CheckReturnValue static <T> FutureAction<T> fromCompletableFuture(@NotNull @NotNull CompletableFuture<T> future, @Nullable @Nullable Executor executor) Creates a new FutureAction from a givenCompletableFuture.- Type Parameters:
T- The return type of the task.- Parameters:
future- ACompletableFutureprovided.executor- The executor to run the task on. If null, falls back to the default IO executor.- Returns:
- A new FutureAction instance.
-
completed
Creates a FutureAction that is already completed with the given value.- Type Parameters:
T- The type of the value.- Parameters:
value- The value to complete the action with.- Returns:
- A completed FutureAction.
-
collect
@SafeVarargs @NotNull @CheckReturnValue static <E> @NotNull FutureAction<List<E>> collect(@NotNull @NotNull FutureAction<? extends E>... actions) Sequences multiple actions to run sequentially (one after another). This is useful to avoid rate-limiting issues when dispatching multiple heavy requests.- Type Parameters:
E- The return type of the actions.- Parameters:
actions- The actions to execute sequentially.- Returns:
- A single FutureAction containing a List of all results in order.
-
collectParallel
@SafeVarargs @NotNull @CheckReturnValue static <E> @NotNull FutureAction<List<E>> collectParallel(@NotNull @NotNull FutureAction<? extends E>... actions) Dispatches multiple actions to run in parallel simultaneously. The overall execution time will be roughly equal to the longest individual action.- Type Parameters:
E- The return type of the actions.- Parameters:
actions- The actions to execute concurrently.- Returns:
- A single FutureAction containing a List of all results.
-
setChecks
@CheckReturnValue @NotNull @NotNull FutureAction<T> setChecks(@Nullable @Nullable BooleanSupplier checks) Sets a condition (check) that must returntruebefore the action is executed. If the check returnsfalse, the action is silently cancelled. This overrides any previously set checks.- Parameters:
checks- The condition to check before execution, or null to clear checks.- Returns:
- The current FutureAction instance for chaining.
-
getChecks
- Returns:
- The currently configured execution check, or null if none is set.
-
addCheck
@NotNull @CheckReturnValue default @NotNull FutureAction<T> addCheck(@NotNull @NotNull BooleanSupplier checks) Appends a new check to the existing ones using a logical AND (invalid input: '&'invalid input: '&'). Both the existing checks and the new check must pass for the action to execute.- Parameters:
checks- The new condition to append.- Returns:
- The current FutureAction instance for chaining.
-
deadline
Sets an absolute Unix timestamp deadline for this action. If execution begins after this timestamp, the action will be silently cancelled.- Parameters:
timestamp- The deadline timestamp in milliseconds.- Returns:
- The current FutureAction instance for chaining.
-
timeout
@CheckReturnValue @NotNull default @NotNull FutureAction<T> timeout(long timeout, @NotNull @NotNull TimeUnit unit) Sets a relative timeout for this action.- Parameters:
timeout- The duration to wait before timing out.unit- The time unit for the timeout parameter.- Returns:
- The current FutureAction instance for chaining.
-
retryIfError
@ReleasedSince("26.9.3") @NotNull @CheckReturnValue default @NotNull FutureAction<T> retryIfError(int retries) Retries this action immediately up to the specified maximum attempts if an error occurs.- Parameters:
retries- The maximum number of retry attempts. Must be non-negative.- Returns:
- A new
FutureActionequipped with immediate retry capabilities.
-
retryIfError
@ReleasedSince("26.9.3") @NotNull @CheckReturnValue default @NotNull FutureAction<T> retryIfError(int retries, @NotNull @NotNull Duration delay) Retries this action with a fixed backoff delay between attempts if an error occurs.- Parameters:
retries- The maximum number of retry attempts. Must be non-negative.delay- The fixed backoffDurationto wait before each retry attempt.- Returns:
- A new
FutureActionequipped with delayed retry capabilities.
-
retryIfError
@ReleasedSince("26.9.3") @NotNull @CheckReturnValue default @NotNull FutureAction<T> retryIfError(int retries, @NotNull @NotNull Duration delay, @Nullable @Nullable Runnable onRetry) Retries this action with a fixed backoff delay and an execution hook invoked prior to each retry.- Parameters:
retries- The maximum number of retry attempts. Must be non-negative.delay- The fixed backoffDurationto wait before each retry attempt.onRetry- ARunnablehook invoked before dispatching each retry attempt (e.g., for logging).- Returns:
- A new
FutureActionequipped with intercepted retry capabilities.
-
retryIfError
@NotNull @CheckReturnValue default @NotNull FutureAction<T> retryIfError(int retries, @NotNull @NotNull Duration delay, @Nullable @Nullable Runnable onRetry, @Nullable @Nullable Predicate<? super Throwable> condition) Retries this action using a comprehensive set of shortcut configurations including backoff, lifecycle hook, and error filtering.- Parameters:
retries- The maximum number of retry attempts. Must be non-negative.delay- The fixed backoffDurationto wait before each retry attempt.onRetry- ARunnablehook invoked before dispatching each retry attempt.condition- A predicate to filter which exceptions qualify for a retry. Ifnull, retries on any exception.- Returns:
- A new
FutureActionequipped with conditionally filtered retry capabilities.
-
retryWhen
Retries this action based on a custom retry strategy defined by aRetrypolicy.- Parameters:
retry- TheRetrystrategy detailing attempt limits, backoff periods, listeners, and error filters.- Returns:
- A new
FutureActionconfigured with the specified retry policy.
-
queue
default void queue()Submits the action for asynchronous execution. Success and failure will be handled by the default callbacks. -
queue
Submits the action for asynchronous execution with a specific success callback.- Parameters:
success- The callback triggered when the action completes successfully.
-
queue
void queue(@Nullable @Nullable Consumer<? super T> success, @Nullable @Nullable Consumer<? super Throwable> failure) Submits the action for asynchronous execution with specific success and failure callbacks.- Parameters:
success- The callback triggered upon successful execution.failure- The callback triggered if an exception occurs.
-
complete
Blocks the current thread and executes the action synchronously.- Returns:
- The result of the action.
- Throws:
RuntimeException- if the action fails.
-
complete
Blocks the current thread and executes the action synchronously.- Parameters:
shouldQueue- Whether it should be queued internally.- Returns:
- The result of the action.
-
complete
Blocks the current thread to execute the action synchronously, with a maximum waiting time.- Parameters:
timeout- The maximum time to wait.unit- The time unit of the timeout argument.- Returns:
- The result of the action.
- Throws:
TimeoutException- if the wait timed out.
-
submit
Submits the action for asynchronous execution and returns aCompletableFuture.- Returns:
- A CompletableFuture representing the pending result of the action.
-
submit
Submits the action and returns aCompletableFuture.- Parameters:
shouldQueue- Whether it should be evaluated in the queue immediately.- Returns:
- A CompletableFuture representing the pending result.
-
recover
@NotNull @CheckReturnValue @NotNull FutureAction<T> recover(@NotNull @NotNull Function<Throwable, T> fallback) Recovers from an exception by providing a fallback value. If the action fails, the fallback function is called to supply an alternative successful result.- Parameters:
fallback- The function to provide a fallback value based on the thrown exception.- Returns:
- A new FutureAction containing the original or recovered value.
-
map
@NotNull @CheckReturnValue <U> @NotNull FutureAction<U> map(@NotNull @NotNull Function<? super T, ? extends U> mapper) Transforms the result of this action using the provided mapping function.- Type Parameters:
U- The type of the new result.- Parameters:
mapper- The function to transform the result.- Returns:
- A new FutureAction containing the transformed result.
-
flatMap
@NotNull @CheckReturnValue <U> @NotNull FutureAction<U> flatMap(@NotNull @NotNull Function<? super T, ? extends FutureAction<U>> mapper) Chains another asynchronous action to run after this one completes successfully.- Type Parameters:
U- The result type of the subsequent action.- Parameters:
mapper- The function returning the next FutureAction to execute.- Returns:
- A new FutureAction representing the chained execution.
-
mapToResult
Maps the output of this action into a safeFutureAction.Resultwrapper, which encapsulates either the success value or the thrown exception.- Returns:
- A new FutureAction yielding a Result wrapper.
-
and
@NotNull @CheckReturnValue default <U,O> @NotNull FutureAction<O> and(@NotNull @NotNull FutureAction<U> other, @NotNull @NotNull BiFunction<? super T, ? super U, ? extends O> accumulator) Combines the result of this action with another action using an accumulator function.- Type Parameters:
U- The result type of the second action.O- The final composed output type.- Parameters:
other- The second action to execute.accumulator- The function that combines both results.- Returns:
- A new FutureAction containing the combined result.
-
zip
@NotNull @CheckReturnValue default @NotNull FutureAction<List<T>> zip(@NotNull @NotNull FutureAction<? extends T> first, @NotNull @NotNull FutureAction<? extends T>... other) Zips the results of multiple actions together in parallel execution.- Parameters:
first- The first additional action to run.other- Further actions to run.- Returns:
- A FutureAction that yields a List of all results.
-
onErrorMap
@CheckReturnValue default FutureAction<T> onErrorMap(@NotNull @NotNull Function<? super Throwable, ? extends T> map) Maps the exception thrown by this action into a default successful result.- Parameters:
map- The function to map the throwable to a successful result.- Returns:
- A new FutureAction containing the recovered result.
-
onErrorMap
@CheckReturnValue FutureAction<T> onErrorMap(@Nullable @Nullable Predicate<? super Throwable> condition, @NotNull @NotNull Function<? super Throwable, ? extends T> map) Conditionally maps the exception into a successful result.- Parameters:
condition- The predicate that must be met to apply the error mapping.map- The mapping function.- Returns:
- A new FutureAction.
-
onErrorFlatMap
@CheckReturnValue FutureAction<T> onErrorFlatMap(@Nullable @Nullable Predicate<? super Throwable> condition, @NotNull @NotNull Function<? super Throwable, ? extends FutureAction<? extends T>> map) Conditionally handles an exception by returning an entirely new asynchronous fallback action.- Parameters:
condition- The predicate to trigger the fallback.map- The function returning the fallback FutureAction.- Returns:
- A new FutureAction.
-
onErrorReturn
Directly returns a hardcoded fallback value if an exception occurs.- Parameters:
fallback- The fallback value.- Returns:
- A new FutureAction.
-
onSuccess
@CheckReturnValue @NotNull @NotNull FutureAction<T> onSuccess(@NotNull @NotNull Consumer<? super T> con) Appends a success callback without interrupting the chain.- Parameters:
con- The callback to execute on success.- Returns:
- The current FutureAction instance.
-
onFailure
@CheckReturnValue @NotNull @NotNull FutureAction<T> onFailure(@NotNull @NotNull Consumer<? super Throwable> failure) Appends a failure callback without interrupting the chain.- Parameters:
failure- The callback to execute on failure.- Returns:
- The current FutureAction instance.
-
delay
@NotNull @CheckReturnValue default @NotNull FutureAction<T> delay(long delay, @NotNull @NotNull TimeUnit unit) Delays the execution or completion of this action by a specified duration.- Parameters:
delay- The amount of time to delay.unit- The time unit.- Returns:
- A new FutureAction that will yield the result after the delay.
-
queueAfter
-
queueAfter
-
queueAfter
default void queueAfter(long delay, @NotNull @NotNull TimeUnit unit, @Nullable @Nullable Consumer<? super T> success, @Nullable @Nullable Consumer<? super Throwable> failure) Queues the action asynchronously after waiting for a specified delay.- Parameters:
delay- The delay duration.unit- The time unit.success- Success callback.failure- Failure callback.
-
onExecutor
Transfers the completion processing of this action to a specific executor.- Parameters:
executor- The target executor.- Returns:
- A new FutureAction handling continuations on the specified executor.
-
cancel
boolean cancel(boolean mayInterruptIfRunning) -
isDone
boolean isDone() -
isCancelled
boolean isCancelled()
-