CompletableFuture · Topic 6 of 6
Timeouts and your own executor
Definition​
Always limit how long you wait: orTimeout fails the future after a time, and completeOnTimeout gives a default value instead. For blocking work, pass your own executor to the Async methods instead of using the shared common pool.
Example code​
A slow call that is cut off, running on a dedicated pool
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Demo {
public static void main(String[] args) {
ExecutorService ioPool = Executors.newFixedThreadPool(4); // a pool just for blocking calls
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(2_000); } catch (InterruptedException ignored) { }
return "late answer";
}, ioPool);
String result = slow
.completeOnTimeout("default answer", 200, TimeUnit.MILLISECONDS) // give up after 200 ms
.join();
System.out.println(result);
CompletableFuture<String> strict = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(2_000); } catch (InterruptedException ignored) { }
return "late";
}, ioPool).orTimeout(200, TimeUnit.MILLISECONDS); // fail after 200 ms
try {
strict.join();
} catch (java.util.concurrent.CompletionException e) {
System.out.println("timed out: " + e.getCause().getClass().getSimpleName());
}
ioPool.shutdownNow();
}
}
// Output:
// default answer
// timed out: TimeoutException
Finished this page? Track your progress (saved only in your browser).