What Is CompletableFuture Class

Posted By : Harish Modi | 30-May-2018


CompletableFuture is

new feature of java 8.CompletableFuture class is used for asynchronous programming in Java.
and CompletableFuture class implements the Future Interface.when use of CompletableFuture your main thread does not wait/block
for the completion of the task and it can
execute

other task in parallel.

  • Creating a CompletableFuture-

CompletableFuture<String> completableFuture = new CompletableFuture<String>();

  • Using some method:

1:runAsync():If you want to run some background task asynchronously and don’t want to return anything from the task.

Example:

// Using Lambda Expression
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    // Simulate a long-running Job   
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    System.out.println(" run in a separate thread.");
});

2:supplyAsync(): if you want to return some result from your background task then use supplyAsync()

example:

// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
    @Override
    public String get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of the asynchronous computation";
    }
});

3: thenApply():if you want to process and transform the result of a CompletableFuture when it arrives then use thenApply() method.

example:

// Create a CompletableFuture
CompletableFuture<String> whatsYourNameFuture = CompletableFuture.supplyAsync(() -> {
   try {
       TimeUnit.SECONDS.sleep(1);
   } catch (InterruptedException e) {
       throw new IllegalStateException(e);
   }
   return "Raj";
});

// Attach a callback to the Future using thenApply()
CompletableFuture<String> greetingFuture = whatsYourNameFuture.thenApply(name -> {
   return "Hello " + name;
});

 

 

 

About Author

Author Image
Harish Modi

Harish Modi is good in core java, advance java, springBoot. He is ASSOCIATE CONSULTANT - DEVELOPMENT. and Keen to learn new Skills.

Request for Proposal

Name is required

Comment is required

Sending message..