By kswaughs | Monday, June 22, 2020

Java CompleteableFuture Example

CompleteableFuture is an extension to Java's Future API that allows us to write a non-blocking code.

It runs a task on a separate thread and notifies the main thread about its completion or failure.

ForkJoinPool.commonPool() is the default thread pool that runs the task.
package com.kswaughs.examples;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kswaughs.model.Book;

public class CompleteableFutureExample {

    private static Logger log = LoggerFactory.getLogger("CompleteableFutureExample");

    public static void main(String[] args) {

        CompletableFuture<Book> resultbook = CompletableFuture.supplyAsync(() -> {
  "I am Taking 3 secs to return a book");
            // Sleep for 3 seconds..
            return getBook();

        resultbook.thenAccept(book -> {
  "Book received: \n {}", book);
        });"I am not waiting for the book object");"I will continue with other work..");

        // To prevent this program from terminating prematurely
        ForkJoinPool.commonPool().awaitQuiescence(10, TimeUnit.SECONDS);

    private static Book getBook() {

        Book book = new Book();

        book.setAuthor("John Grisham");
        book.setTitle("A Painted House");"Returning book object");

        return book;

    private static void sleep(int waitTime) {
        try {
        } catch (InterruptedException e) {


21:01:42.742 [main] INFO CompleteableFutureExample - I am not waiting for the book object
21:01:42.742 [ForkJoinPool.commonPool-worker-1] INFO CompleteableFutureExample - I am Taking 3 secs to return a book
21:01:42.744 [main] INFO CompleteableFutureExample - I will continue with other work..
21:01:45.745 [ForkJoinPool.commonPool-worker-1] INFO CompleteableFutureExample - Returning book object
21:01:45.745 [main] INFO CompleteableFutureExample - Book received: 
 Book [bookId=123, title=A Painted House, author=John Grisham]

Recommend this on