pl.allegro.tech.hermes.consumers.consumer.sender.timeout.FutureAsyncTimeout Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of hermes-consumers Show documentation
Show all versions of hermes-consumers Show documentation
Fast and reliable message broker built on top of Kafka.
package pl.allegro.tech.hermes.consumers.consumer.sender.timeout;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Function;
/**
* see http://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html
*/
public class FutureAsyncTimeout {
private final ScheduledExecutorService executor;
public FutureAsyncTimeout(ScheduledExecutorService scheduledExecutorService) {
this.executor = scheduledExecutorService;
}
public CompletableFuture within(CompletableFuture future, Duration duration, Function exceptionMapper) {
return future.applyToEither(failAfter(duration, exceptionMapper), Function.identity());
}
private CompletableFuture failAfter(Duration duration, Function exceptionMapper) {
final CompletableFuture promise = new CompletableFuture<>();
executor.schedule(() -> {
TimeoutException ex = new TimeoutException("Timeout after " + duration);
return promise.complete(exceptionMapper.apply(ex));
}, duration.toMillis(), TimeUnit.MILLISECONDS);
return promise;
}
public void shutdown() {
executor.shutdown();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy