TimeLimiter
Getting started with resilience4j-timelimiter
Create a TimeLimiterRegistry
Just like the CircuitBreaker module, this module provides an in-memory TimeLimiterRegistry
which you can use to manage (create and retrieve) TimeLimiter instances.
TimeLimiterRegistry timeLimiterRegistry = TimeLimiterRegistry.ofDefaults();
Create and configure TimeLimiter
You can provide a custom global TimeLimiterConfig. In order to create a custom global TimeLimiterConfig, you can use the TimeLimiterConfig builder. You can use the builder to configure:
- the timeout duration
- whether cancel should be called on the running future
TimeLimiterConfig config = TimeLimiterConfig.custom()
.cancelRunningFuture(true)
.timeoutDuration(Duration.ofMillis(500))
.build();
// Create a TimeLimiterRegistry with a custom global configuration
TimeLimiterRegistry timeLimiterRegistry = TimeLimiterRegistry.of(config);
// Get or create a TimeLimiter from the registry -
// TimeLimiter will be backed by the default config
TimeLimiter timeLimiterWithDefaultConfig = registry.timeLimiter("name1");
// Get or create a TimeLimiter from the registry,
// use a custom configuration when creating the TimeLimiter
TimeLimiterConfig config = TimeLimiterConfig.custom()
.cancelRunningFuture(false)
.timeoutDuration(Duration.ofMillis(1000))
.build();
TimeLimiter timeLimiterWithCustomConfig = registry.timeLimiter("name2", config);
Decorate and execute a functional interface
TimeLimiter has higher order decorator functions to decorate a CompletionStage
or Future
in order to limit the execution time.
// Given I have a helloWorldService.sayHelloWorld() method which takes too long
HelloWorldService helloWorldService = mock(HelloWorldService.class);
// Create a TimeLimiter
TimeLimiter timeLimiter = TimeLimiter.of(Duration.ofSeconds(1));
// The Scheduler is needed to schedule a timeout on a non-blocking CompletableFuture
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
// The non-blocking variant with a CompletableFuture
CompletableFuture<String> result = timeLimiter.executeCompletionStage(
scheduler, () -> CompletableFuture.supplyAsync(helloWorldService::sayHelloWorld)).toCompletableFuture();
// The blocking variant which is basically future.get(timeoutDuration, MILLISECONDS)
String result = timeLimiter.executeFutureSupplier(
() -> CompletableFuture.supplyAsync(() -> helloWorldService::sayHelloWorld));
Updated over 4 years ago