CompletableFuture with timeout

Two CompletableFutures  can be combined to timeout the CompletableFuture with the business logic like below:

 package competablefuture;

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 CompletableFutureSample {

static ScheduledExecutorService pool = Executors.newScheduledThreadPool(4);

public static CompletableFuture executeAsyncTimed(Duration duration) {

final CompletableFuture asyncTimedFuture = new CompletableFuture<>();

pool.schedule(() -> asyncTimedFuture.completeExceptionally(new TimeoutException()), duration.toMillis(), TimeUnit.MILLISECONDS);
 return asyncTimedFuture;


public static void main(String[] args) {
 final CompletableFuture businessLogicFuture = businessLogicCall();
 final CompletableFuture timeoutFuture = executeAsyncTimed(Duration.ofSeconds(1));

businessLogicFuture.applyToEither(timeoutFuture, x -> x);

private static CompletableFuture businessLogicCall() {

return new CompletableFuture(); //hier, method returns a completablefuture with business logic

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s