Here you can find the source of futureWithTimeout(Duration timeout, ScheduledExecutorService executorService)
Parameter | Description |
---|---|
timeout | The timeout for the future. |
executorService | An ExecutorService that will be used to invoke the timeout on. |
T | The Type argument for the CompletableFuture to create. |
public static <T> CompletableFuture<T> futureWithTimeout(Duration timeout, ScheduledExecutorService executorService)
//package com.java2s; /**/*www.jav a 2s . c o m*/ * Copyright (c) 2017 Dell Inc., or its subsidiaries. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 */ import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; public class Main { /** * Creates a new CompletableFuture that will timeout after the given amount of time. * * @param timeout The timeout for the future. * @param executorService An ExecutorService that will be used to invoke the timeout on. * @param <T> The Type argument for the CompletableFuture to create. * @return A CompletableFuture with a timeout. */ public static <T> CompletableFuture<T> futureWithTimeout(Duration timeout, ScheduledExecutorService executorService) { return futureWithTimeout(timeout, null, executorService); } /** * Creates a new CompletableFuture that will timeout after the given amount of time. * * @param timeout The timeout for the future. * @param tag A tag (identifier) to be used as a parameter to the TimeoutException. * @param executorService An ExecutorService that will be used to invoke the timeout on. * @param <T> The Type argument for the CompletableFuture to create. * @return The result. */ public static <T> CompletableFuture<T> futureWithTimeout(Duration timeout, String tag, ScheduledExecutorService executorService) { CompletableFuture<T> result = new CompletableFuture<>(); ScheduledFuture<Boolean> sf = executorService.schedule( () -> result.completeExceptionally(new TimeoutException(tag)), timeout.toMillis(), TimeUnit.MILLISECONDS); result.whenComplete((r, ex) -> sf.cancel(true)); return result; } }