Failsafe is a simple, lightweight library for handling failures in Java applications. In this article, we are going to present some of the features that
Schedulers in Failsafe library
In order to perform asynchronous executions
Failsafe library uses
ForkJoinPool.commonPool but we can also configure a specific
ExecutorService that can be used instead.
We can supply your executor via the
Failsafe supports event listeners that allow monitoring executions.
There are different listeners for:
- Failsafe Executor,
- Policy implementations.
At the top level of
Failsafe API, we are getting notifications when an execution:
- completes successfully for all policies,
- fails for any policy,
- completes for all policies.
At the policy level, Failsafe can notify you when an execution succeeds or fails for a particular policy:
Failsafe executions are typed based on the expected result. We can declare common
Object type and more specific result types like in the following example:
Failsafe execution will look like the following:
Failsafe library provide information about the execution such as the number of execution attempts, start and elapsed times, and the last result or failure:
Execution context is useful if we want to create an execution that depends on results from a previous attempt.
Failsafe supports cancellation and optional interruption of executions:
- Cancellation will cause any async execution retries and timeout attempts to stop,
- Interruption will cause the execution thread’s interrupt flag to be set.
Cancellations can be triggered by Timeout. Interruptions could be triggered manually like in the following code:
In the execution code we can check if it was cancelled:
Async API Support
Failsafe can be integrated with asynchronous code that reports completion via callbacks. The runAsyncExecution, getAsyncExecution, and getStageAsyncExecution methods provide an AsyncExecution reference that can be used to manually schedule retries or complete the execution from inside asynchronous callbacks.
CompletionStage Object Support
Failsafe can accept a CompletionStage and return a new CompletableFuture with failure handling built-in:
Functional Interface Support
Failsafe can be used to create resilient functional interfaces.
Execution tracking is a useful feature for integrating with APIs that have their retry mechanism. We can configure Failsafe to manually retry executions as needed.
In this article, we showcased several features that come with
Failsafe. This useful library allows us to control completely executions, monitor them, and cancel when we want to. Failsafe supports 'modern' Java interfaces like
CompletableFuture which makes it extremely easy to integrate into modern applications.