All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pl.allegro.tech.hermes.consumers.consumer.sender.timeout.FutureAsyncTimeout Maven / Gradle / Ivy

There is a newer version: 2.8.0
Show newest version
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