Timeout

  1. Timeouts with Retries
  2. Async Execution Timeouts
  3. Event Listeners
  4. Limitations

Timeouts allow you to fail an execution with TimeoutExceededException if it takes too long to complete:

Timeout<Object> timeout = Timeout.of(Duration.ofSeconds(10));

You can also interrupt an execution if it times out:

timeout.withInterrupt(true);

If a cancellation is triggered by a Timeout, the execution is completed with TimeoutExceededException. See the execution cancellation page for more on cancellation and interruption.

Timeouts with Retries

When a Timeout is composed outside a RetryPolicy, a timeout occurrence will cancel any inner retries:

Failsafe.with(timeout, retryPolicy).run(this::connect);

When a Timeout is composed inside a RetryPolicy, a timeout occurrence will not automically cancel any outer retries:

Failsafe.with(retryPolicy, timeout).run(this::connect);

Async Execution Timeouts

When an async executions times out, Failsafe still waits until the execution completes, either through interruption or naturally, before recording a TimeoutExceededException. This avoids the risk of retrying while the original execution is still running, which ultimately could lead to numerous abandoned executions running in numerous threads.

Event Listeners

Timeouts support the standard policy listeners which can notify you when a timeout is exceeded:

timeout.onFailure(e -> log.error("Connection attempt timed out", e.getFailure()));

Or when an execution completes and the timeout is not exceeded:

timeout.onSuccess(e -> log.info("Execution completed on time"));

Limitations

Since the async integration methods involve external threads, which Failsafe has no knowledge of, these executions cannot be directly cancelled or interrupted by a Timeout. But, these executions can still cooperate with a Timeout cancellation.