com.smaato.switchgear.circuitbreaker.TimeoutScheduler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of switchgear Show documentation
Show all versions of switchgear Show documentation
Switchgear is a Java library that provides an API for call isolation, timeouts, and circuit breaker
functionality. Our main goal is to achieve minimal performance overhead of the library, even when used in the
hottest place of your application. Additionally, we've opted for zero transitive dependencies and maintaining a
fluent API.
The newest version!
package com.smaato.switchgear.circuitbreaker;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import com.smaato.switchgear.circuitbreaker.state.bucket.BucketRange;
class TimeoutScheduler {
private static final boolean DO_NOT_INTERRUPT = false;
private final ScheduledExecutorService scheduler;
TimeoutScheduler(final ScheduledExecutorService scheduler) {
this.scheduler = scheduler;
}
Supplier> addTimeout(final Supplier> futureSupplier,
final int timeoutInMillis,
final BucketRange timeoutBucketRange) {
return () -> scheduleTimeout(futureSupplier.get(), timeoutInMillis, timeoutBucketRange);
}
private CompletableFuture scheduleTimeout(final CompletableFuture future,
final int timeoutInMillis,
final BucketRange timeoutBucketRange) {
final ScheduledFuture> timeoutCheckFuture = scheduler.schedule(() -> {
if (!future.isDone()) {
future.completeExceptionally(TimeoutExceptionBuilder.builder().withTimeoutRange(timeoutBucketRange).build());
}
}, timeoutInMillis, TimeUnit.MILLISECONDS);
// Configure the event future to delete the timeout check immediately when it finishes.
future.whenComplete((event, error) -> {
if (!timeoutCheckFuture.isDone()) {
timeoutCheckFuture.cancel(DO_NOT_INTERRUPT);
}
});
return future;
}
}