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.

CompleteableFutureExample.java
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(() -> {
            log.info("I am Taking 3 secs to return a book");
            // Sleep for 3 seconds..
            sleep(3000);
            return getBook();
        });

        resultbook.thenAccept(book -> {
            log.info("Book received: \n {}", book);
        });

        log.info("I am not waiting for the book object");
        log.info("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.setBookId(123);
        book.setAuthor("John Grisham");
        book.setTitle("A Painted House");

        log.info("Returning book object");

        return book;
    }

    private static void sleep(int waitTime) {
        try {
            Thread.sleep(waitTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output

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