Java Duration Calculate failAfter(Duration duration)

Here you can find the source of failAfter(Duration duration)

Description

Generates a completable future which times out.

License

Apache License

Parameter

Parameter Description
duration The duration to timeout after.
T Ignored, since the future will always timeout.

Return

A completable future that will time out.

Declaration

public static <T> CompletableFuture<T> failAfter(Duration duration) 

Method Source Code

    //package com.java2s;
    //License from project: Apache License 

    import com.google.common.util.concurrent.ThreadFactoryBuilder;
    import java.time.Duration;
    import java.util.concurrent.CompletableFuture;

    import java.util.concurrent.Executors;

    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;

    public class Main {
        private static final ScheduledExecutorService scheduler = Executors
                .newScheduledThreadPool(1, new ThreadFactoryBuilder()
                        .setDaemon(true).setNameFormat("failAfter-%d").build());

        /**/*from   www  .  java2 s .co  m*/
         * Generates a completable future which times out.
         * inspired by NoBlogDefFound: http://www.nurkiewicz.com/2014/12/asynchronous-timeouts-with.html
         *
         * @param duration The duration to timeout after.
         * @param <T>      Ignored, since the future will always timeout.
         * @return A completable future that will time out.
         */
        public static <T> CompletableFuture<T> failAfter(Duration duration) {
    final CompletableFuture<T> promise = new CompletableFuture<>();
    scheduler.schedule(() -> {
        final TimeoutException ex = new TimeoutException("Timeout after "
                + duration.toMillis() + " ms");
        return promise.completeExceptionally(ex);
    }, duration.toMillis(), TimeUnit.MILLISECONDS);
    return promise;
}
    }

Related

  1. awaitTermination(ExecutorService service, Logger logger, Duration timeout, String technique)
  2. calculateDuration(Duration minimum, Duration maximum, Long iteration)
  3. daysRoundingUp(Duration duration)
  4. delayedFuture(Duration delay, ScheduledExecutorService executorService)
  5. durationFromNow(TemporalAmount duration)
  6. futureWithTimeout(Duration timeout, ScheduledExecutorService executorService)
  7. getDurationAsISO8601(Duration duration)
  8. getDurationByTimeValues(final long hours, final long minutes, final long seconds)
  9. getExpirationMillis(long now, Duration duration)