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


2 comments:

  1. Great tutorial. Java provides several complex classes for various applications. Learning algorithm and data structures in Java is essential to develop solid problem-solving skills. Thank you for sharing this.

    ReplyDelete
  2. 가상화폐 도박사이트 You might have a lot enjoyable actively playing football. But, you need to take things a bit more by getting some information that will help you with the soccer online game. Really, soccer is an excellent sports activity, and you also are planning to learn some very nice ideas. Keep reading to be able to display you are a excellent soccer participant.Try pushing the ball using the inside of your feet if you have to shield it. This provides you with more control and then make it tough for the defender to take it of your stuff. Use your overall body to defend the tennis ball in the defender to check out another person you are able to pass the soccer ball to.Every one of the practice drills in the world won't assist your game when you lack the bodily stamina to experience the complete match. Establish a sprinting or cardio exercise plan that will enable you to build up your vigor. You will discover it simpler to execute in the area once you aren't fatigued.

    ReplyDelete