Class FailsafeExecutor<R>
- java.lang.Object
-
- dev.failsafe.FailsafeExecutor<R>
-
- Type Parameters:
R- result type
public class FailsafeExecutor<R> extends java.lang.ObjectAn executor that handles failures according to configured
policies. Can be created viaFailsafe.with(Policy, Policy[])to support policy based execution failure handling, orFailsafe.none()to support execution with no failure handling.Async executions are run by default on the
ForkJoinPool.commonPool(). Alternative executors can be configured viawith(ScheduledExecutorService)and similar methods. All async executions are cancellable and interruptable via the returned CompletableFuture, even those run by aForkJoinPoolorCompletionStage.
-
-
Field Summary
Fields Modifier and Type Field Description private EventHandler<R>completeHandler(package private) java.util.function.BiConsumer<ExecutionResult<R>,ExecutionContext<R>>completionHandlerprivate java.util.concurrent.Executorexecutorprivate EventHandler<R>failureHandler(package private) java.util.List<? extends Policy<R>>policiesPolicies sorted outermost firstprivate Schedulerschedulerprivate EventHandler<R>successHandler
-
Constructor Summary
Constructors Constructor Description FailsafeExecutor(java.util.List<? extends Policy<R>> policies)
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description private <T> Tcall(ContextualSupplier<T,T> innerSupplier)Calls theinnerSuppliersynchronously, handling results according to the configured policies.private <T> java.util.concurrent.CompletableFuture<T>callAsync(java.util.function.Function<FailsafeFuture<T>,java.util.function.Function<AsyncExecutionInternal<T>,java.util.concurrent.CompletableFuture<ExecutionResult<T>>>> innerFn, boolean asyncExecution)Calls the asynchronousinnerFnvia the configured Scheduler, handling results according to the configured policies.private <T> Call<T>callSync(ContextualSupplier<T,T> innerSupplier)Returns a Call that calls theinnerSuppliersynchronously, handling results according to the configured policies.<P extends Policy<R>>
FailsafeExecutor<R>compose(P innerPolicy)Returns a newFailsafeExecutorthat composes the currently configured policies around the giveninnerPolicy.<T extends R>
Tget(CheckedSupplier<T> supplier)Executes thesupplieruntil a successful result is returned or the configured policies are exceeded.<T extends R>
Tget(ContextualSupplier<T,T> supplier)Executes thesupplieruntil a successful result is returned or the configured policies are exceeded.<T extends R>
java.util.concurrent.CompletableFuture<T>getAsync(CheckedSupplier<T> supplier)Executes thesupplierasynchronously until a successful result is returned or the configured policies are exceeded.<T extends R>
java.util.concurrent.CompletableFuture<T>getAsync(ContextualSupplier<T,T> supplier)Executes thesupplierasynchronously until a successful result is returned or the configured policies are exceeded.<T extends R>
java.util.concurrent.CompletableFuture<T>getAsyncExecution(AsyncRunnable<T> runnable)This method is intended for integration with asynchronous code.java.util.List<? extends Policy<R>>getPolicies()Returns the currently configured policies.<T extends R>
java.util.concurrent.CompletableFuture<T>getStageAsync(CheckedSupplier<? extends java.util.concurrent.CompletionStage<T>> supplier)Executes thesupplierasynchronously until the resulting future is successfully completed or the configured policies are exceeded.<T extends R>
java.util.concurrent.CompletableFuture<T>getStageAsync(ContextualSupplier<T,? extends java.util.concurrent.CompletionStage<T>> supplier)Executes thesupplierasynchronously until the resulting future is successfully completed or the configured policies are exceeded.Call<java.lang.Void>newCall(ContextualRunnable<java.lang.Void> runnable)Returns a call that can execute therunnableuntil a successful result is returned or the configured policies are exceeded.<T extends R>
Call<T>newCall(ContextualSupplier<T,T> supplier)Returns a call that can execute thesupplieruntil a successful result is returned or the configured policies are exceeded.FailsafeExecutor<R>onComplete(EventListener<ExecutionCompletedEvent<R>> listener)Registers thelistenerto be called when an execution is complete.FailsafeExecutor<R>onFailure(EventListener<ExecutionCompletedEvent<R>> listener)Registers thelistenerto be called when an execution fails.FailsafeExecutor<R>onSuccess(EventListener<ExecutionCompletedEvent<R>> listener)Registers thelistenerto be called when an execution is successful.voidrun(CheckedRunnable runnable)Executes therunnableuntil successful or until the configured policies are exceeded.voidrun(ContextualRunnable<java.lang.Void> runnable)Executes therunnableuntil successful or until the configured policies are exceeded.java.util.concurrent.CompletableFuture<java.lang.Void>runAsync(CheckedRunnable runnable)Executes therunnableasynchronously until successful or until the configured policies are exceeded.java.util.concurrent.CompletableFuture<java.lang.Void>runAsync(ContextualRunnable<java.lang.Void> runnable)Executes therunnableasynchronously until successful or until the configured policies are exceeded.java.util.concurrent.CompletableFuture<java.lang.Void>runAsyncExecution(AsyncRunnable<java.lang.Void> runnable)This method is intended for integration with asynchronous code.FailsafeExecutor<R>with(Scheduler scheduler)Configures theschedulerto use for performing asynchronous executions and listener callbacks.FailsafeExecutor<R>with(java.util.concurrent.Executor executor)Configures theexecutorto use as a wrapper around executions.FailsafeExecutor<R>with(java.util.concurrent.ExecutorService executorService)Configures theexecutorServiceto use for performing asynchronous executions and listener callbacks.FailsafeExecutor<R>with(java.util.concurrent.ScheduledExecutorService scheduledExecutorService)Configures thescheduledExecutorServiceto use for performing asynchronous executions and listener callbacks.
-
-
-
Field Detail
-
scheduler
private Scheduler scheduler
-
executor
private java.util.concurrent.Executor executor
-
completeHandler
private volatile EventHandler<R> completeHandler
-
failureHandler
private volatile EventHandler<R> failureHandler
-
successHandler
private volatile EventHandler<R> successHandler
-
completionHandler
final java.util.function.BiConsumer<ExecutionResult<R>,ExecutionContext<R>> completionHandler
-
-
Method Detail
-
getPolicies
public java.util.List<? extends Policy<R>> getPolicies()
Returns the currently configured policies.- See Also:
compose(Policy)
-
compose
public <P extends Policy<R>> FailsafeExecutor<R> compose(P innerPolicy)
Returns a newFailsafeExecutorthat composes the currently configured policies around the giveninnerPolicy. For example, consider:Failsafe.with(fallback).compose(retryPolicy).compose(circuitBreaker);
This results in the following internal composition when executing arunnableorsupplierand handling its result:Fallback(RetryPolicy(CircuitBreaker(Supplier)))
This means theCircuitBreakeris first to evaluate theSupplier's result, then theRetryPolicy, then theFallback. Each policy makes its own determination as to whether the result represents a failure. This allows different policies to be used for handling different types of failures.- Throws:
java.lang.NullPointerException- ifinnerPolicyis null- See Also:
getPolicies()
-
get
public <T extends R> T get(CheckedSupplier<T> supplier)
Executes thesupplieruntil a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if thesupplieris nullFailsafeException- if the execution fails with a checked Exception.Throwable.getCause()can be used to learn the underlying checked exception.
-
get
public <T extends R> T get(ContextualSupplier<T,T> supplier)
Executes thesupplieruntil a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if thesupplieris nullFailsafeException- if the execution fails with a checked Exception.Throwable.getCause()can be used to learn the underlying checked exception.
-
newCall
public Call<java.lang.Void> newCall(ContextualRunnable<java.lang.Void> runnable)
Returns a call that can execute therunnableuntil a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if therunnableis null
-
newCall
public <T extends R> Call<T> newCall(ContextualSupplier<T,T> supplier)
Returns a call that can execute thesupplieruntil a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if thesupplieris null
-
getAsync
public <T extends R> java.util.concurrent.CompletableFuture<T> getAsync(CheckedSupplier<T> supplier)
Executes thesupplierasynchronously until a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if thesupplieris nulljava.util.concurrent.RejectedExecutionException- if thesuppliercannot be scheduled for execution
-
getAsync
public <T extends R> java.util.concurrent.CompletableFuture<T> getAsync(ContextualSupplier<T,T> supplier)
Executes thesupplierasynchronously until a successful result is returned or the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if thesupplieris nulljava.util.concurrent.RejectedExecutionException- if thesuppliercannot be scheduled for execution
-
getAsyncExecution
public <T extends R> java.util.concurrent.CompletableFuture<T> getAsyncExecution(AsyncRunnable<T> runnable)
This method is intended for integration with asynchronous code.Executes the
runnableasynchronously until a successful result is recorded or the configured policies are exceeded. Executions must be recorded via one of theAsyncExecution.recordmethods which will trigger failure handling, if needed, by the configured policies, else the resultingCompletableFuturewill be completed. Any exception that is thrown from therunnablewill automatically be recorded viaAsyncExecution.recordException(Throwable).- Throws:
java.lang.NullPointerException- if therunnableis nulljava.util.concurrent.RejectedExecutionException- if therunnablecannot be scheduled for execution
-
getStageAsync
public <T extends R> java.util.concurrent.CompletableFuture<T> getStageAsync(CheckedSupplier<? extends java.util.concurrent.CompletionStage<T>> supplier)
Executes thesupplierasynchronously until the resulting future is successfully completed or the configured policies are exceeded.Cancelling the resulting
CompletableFuturewill automatically cancels the suppliedCompletionStageif it's aFuture.- Throws:
java.lang.NullPointerException- if thesupplieris nulljava.util.concurrent.RejectedExecutionException- if thesuppliercannot be scheduled for execution
-
getStageAsync
public <T extends R> java.util.concurrent.CompletableFuture<T> getStageAsync(ContextualSupplier<T,? extends java.util.concurrent.CompletionStage<T>> supplier)
Executes thesupplierasynchronously until the resulting future is successfully completed or the configured policies are exceeded.Cancelling the resulting
CompletableFuturewill automatically cancels the suppliedCompletionStageif it's aFuture.- Throws:
java.lang.NullPointerException- if thesupplieris nulljava.util.concurrent.RejectedExecutionException- if thesuppliercannot be scheduled for execution
-
run
public void run(CheckedRunnable runnable)
Executes therunnableuntil successful or until the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if therunnableis nullFailsafeException- if the execution fails with a checked Exception.Throwable.getCause()can be used to learn the underlying checked exception.
-
run
public void run(ContextualRunnable<java.lang.Void> runnable)
Executes therunnableuntil successful or until the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if therunnableis nullFailsafeException- if the execution fails with a checked Exception.Throwable.getCause()can be used to learn the underlying checked exception.
-
runAsync
public java.util.concurrent.CompletableFuture<java.lang.Void> runAsync(CheckedRunnable runnable)
Executes therunnableasynchronously until successful or until the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if therunnableis nulljava.util.concurrent.RejectedExecutionException- if therunnablecannot be scheduled for execution
-
runAsync
public java.util.concurrent.CompletableFuture<java.lang.Void> runAsync(ContextualRunnable<java.lang.Void> runnable)
Executes therunnableasynchronously until successful or until the configured policies are exceeded.- Throws:
java.lang.NullPointerException- if therunnableis nulljava.util.concurrent.RejectedExecutionException- if therunnablecannot be scheduled for execution
-
runAsyncExecution
public java.util.concurrent.CompletableFuture<java.lang.Void> runAsyncExecution(AsyncRunnable<java.lang.Void> runnable)
This method is intended for integration with asynchronous code.Executes the
runnableasynchronously until a successful result is recorded or the configured policies are exceeded. Executions must be recorded via one of theAsyncExecution.recordmethods which will trigger failure handling, if needed, by the configured policies, else the resultingCompletableFuturewill be completed. Any exception that is thrown from therunnablewill automatically be recorded viaAsyncExecution.recordException(Throwable).- Throws:
java.lang.NullPointerException- if therunnableis nulljava.util.concurrent.RejectedExecutionException- if therunnablecannot be scheduled for execution
-
onComplete
public FailsafeExecutor<R> onComplete(EventListener<ExecutionCompletedEvent<R>> listener)
Registers thelistenerto be called when an execution is complete. This occurs when an execution is successful according to all policies, or all policies have been exceeded.Note: Any exceptions that are thrown from within the
listenerare ignored.
-
onFailure
public FailsafeExecutor<R> onFailure(EventListener<ExecutionCompletedEvent<R>> listener)
Registers thelistenerto be called when an execution fails. This occurs when the execution fails according to some policy, and all policies have been exceeded.Note: Any exceptions that are thrown from within the
listenerare ignored. To provide an alternative result for a failed execution, use aFallback.
-
onSuccess
public FailsafeExecutor<R> onSuccess(EventListener<ExecutionCompletedEvent<R>> listener)
Registers thelistenerto be called when an execution is successful. If multiple policies, are configured, this handler is called when execution is complete and all policies succeed. If all policies do not succeed, then theonFailure(EventListener)registered listener is called instead.Note: Any exceptions that are thrown from within the
listenerare ignored.
-
with
public FailsafeExecutor<R> with(java.util.concurrent.ScheduledExecutorService scheduledExecutorService)
Configures thescheduledExecutorServiceto use for performing asynchronous executions and listener callbacks.Note: The
scheduledExecutorServiceshould have a core pool size of at least 2 in order fortimeoutsto work.- Throws:
java.lang.NullPointerException- ifscheduledExecutorServiceis nulljava.lang.IllegalArgumentException- if thescheduledExecutorServicehas a core pool size of less than 2
-
with
public FailsafeExecutor<R> with(java.util.concurrent.ExecutorService executorService)
Configures theexecutorServiceto use for performing asynchronous executions and listener callbacks. For async executions that require a delay, an internal ScheduledExecutorService will be used for the delay, then theexecutorServicewill be used for actual execution.Note: The
executorServiceshould have a core pool size or parallelism of at least 2 in order fortimeoutsto work.- Throws:
java.lang.NullPointerException- ifexecutorServiceis null
-
with
public FailsafeExecutor<R> with(java.util.concurrent.Executor executor)
Configures theexecutorto use as a wrapper around executions. If theexecutoris actually an instance ofExecutorService, then theexecutorwill be configured viawith(ExecutorService)instead.The
executoris responsible for propagating executions. Executions that normally return a result, such asget(CheckedSupplier)will returnnullsince theExecutorinterface does not support results.The
executorwill not be used forgetStageAsynccalls since those require a returned result.- Throws:
java.lang.NullPointerException- ifexecutoris null
-
with
public FailsafeExecutor<R> with(Scheduler scheduler)
Configures theschedulerto use for performing asynchronous executions and listener callbacks.- Throws:
java.lang.NullPointerException- ifscheduleris null
-
call
private <T> T call(ContextualSupplier<T,T> innerSupplier)
Calls theinnerSuppliersynchronously, handling results according to the configured policies.
-
callSync
private <T> Call<T> callSync(ContextualSupplier<T,T> innerSupplier)
Returns a Call that calls theinnerSuppliersynchronously, handling results according to the configured policies.
-
callAsync
private <T> java.util.concurrent.CompletableFuture<T> callAsync(java.util.function.Function<FailsafeFuture<T>,java.util.function.Function<AsyncExecutionInternal<T>,java.util.concurrent.CompletableFuture<ExecutionResult<T>>>> innerFn, boolean asyncExecution)
Calls the asynchronousinnerFnvia the configured Scheduler, handling results according to the configured policies.- Parameters:
asyncExecution- whether this is a detached, async execution that must be manually completed- Throws:
java.lang.NullPointerException- if theinnerFnis nulljava.util.concurrent.RejectedExecutionException- if theinnerFncannot be scheduled for execution
-
-