TimeLimiter

Time limiter for enforcing execution timeouts.

The Time Limiter pattern ensures that operations complete within a specified time limit. It provides various strategies for handling timeouts including fallbacks, retries, and statistics tracking.

Use Cases:

  • Prevent operations from hanging indefinitely

  • Enforce SLA requirements

  • Detect slow or unresponsive services

  • Set deadlines for operations

Basic usage:

val limiter = TimeLimiter.create(config = TimeLimiterConfig(timeout = 5.seconds))

val result = limiter.execute {
callSlowService()
} // throws TimeoutCancellationException if > 5s

With fallback:

val result = limiter.executeOrFallback(
fallback = { "default" }
) {
callSlowService()
}

Parallel execution with timeout:

val results = limiter.executeAll(
blocks = listOf(
{ callService1() },
{ callService2() },
{ callService3() }
)
) // returns list with null for timed-out calls

Parameters

config

Configuration for time limiter behavior

Types

Link copied to clipboard
object Companion

Factory for TimeLimiter.

Functions

Link copied to clipboard

Adds a listener for time limiter events.

Link copied to clipboard
suspend fun <T> execute(timeout: Duration? = null, block: suspend () -> T): T

Executes an operation with a timeout.

Link copied to clipboard
suspend fun <T> executeAll(timeout: Duration? = null, blocks: List<suspend () -> T>): List<T?>

Executes multiple operations with individual timeouts.

Link copied to clipboard
suspend fun <T> executeOrDefault(timeout: Duration? = null, default: T, block: suspend () -> T): T

Executes an operation with a timeout and default value.

Link copied to clipboard
suspend fun <T> executeOrFallback(timeout: Duration? = null, fallback: suspend (TimeoutCancellationException) -> T, block: suspend () -> T): T

Executes an operation with a timeout and fallback.

Link copied to clipboard
suspend fun <T> executeOrNull(timeout: Duration? = null, block: suspend () -> T): T?

Executes an operation with a timeout, returning null if it times out.

Link copied to clipboard
suspend fun <T> executeRace(timeout: Duration? = null, blocks: List<suspend () -> T>): T

Executes the first operation that completes within the timeout.

Link copied to clipboard
suspend fun <T> executeWithRetry(timeout: Duration? = null, retries: Int = 3, block: suspend () -> T): T

Executes an operation with a timeout and automatic retry on timeout.

Link copied to clipboard
suspend fun resetStatistics()

Resets all statistics counters.

Link copied to clipboard

Gets the current statistics.

Inherited functions

Link copied to clipboard

Adapts this TimeLimiter into a Policy.