Skip to content

Latest commit

 

History

History

Code examples

The no-arg constructor creates an incomplete future.

CompletableFuture<String> future = new CompletableFuture<>();
assertFalse(future.isDone());

The newIncompleteFuture method creates an incomplete future of the same type as the called CompletableFuture object. You should override this method if you are implementing a subclass of CompletableFuture.

CompletableFuture<String> future1 = CompletableFuture.completedFuture("value");
assertTrue(future1.isDone());
CompletableFuture<String> future2 = future1.newIncompleteFuture();
assertFalse(future2.isDone());

The supplyAsync method creates an incomplete future that is asynchronously completed after it obtains a value from the given Supplier.

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> sleepAndGet("value"));
assertEquals("value", future.get());

The runAsync method creates an incomplete future that is asynchronously completed after it runs an action from the given Runnable.

CompletableFuture<Void> future = CompletableFuture.runAsync(() -> logger.info("action"));
assertNull(future.get());

The completedFuture method creates a normally completed future.

CompletableFuture<String> future = CompletableFuture.completedFuture("value");
assertTrue(future.isDone());
assertFalse(future.isCompletedExceptionally());
assertEquals("value", future.get());

The failedFuture method creates an exceptionally completed future.

CompletableFuture<String> future = CompletableFuture.failedFuture(new RuntimeException("exception"));
assertTrue(future.isDone());
assertTrue(future.isCompletedExceptionally());