Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
thenaccept
completablefuture

What is CompletableFuture.thenAccept() in Java?

abhilash

thenAccept() is an instance method in Java. It is used when we don’t want to return anything from our callback function and only want to run some code once a FutureIt represents the result of an asynchronous computation. completes. This method has access to the result of the CompletableFuture on which it is attached.

The thenAccept method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, use the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


public CompletableFuture<Void> thenAccept(Consumer<? super T> action)

Parameters

  • Consumer<? super T> action: The consumer to execute.

Return value

This method returns a new CompletableFuture.

Code

import java.util.concurrent.*;

public class Main {

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

    static void executionThread(){
        System.out.println("Thread execution - " + Thread.currentThread().getName());
    }

    public static void main(String[] args){

        CompletableFuture<String> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            sleep(1000);
            String stringToPrint = "Educative";
            System.out.println("----\nsupplyAsync first future - " + stringToPrint);
            executionThread();
            return stringToPrint;
        });

        completableFuture1.thenAccept(res -> System.out.println("Future result - " + res));
        sleep(2000);
    }
}
Implementation of the "toAccept" method

Explanation

  • Line 1: We import the relevant packages and classes.
  • Lines 5 to 11: We define a function called sleep() that makes the current thread sleep for the given number of milliseconds.
  • Lines 13 to 15: We define a function called executionThread() that prints the current thread being executed.
  • Lines 19 to 25: We create a completableFuture object called completableFuture1 using the supplyAsyc() method by passing a supplier that sleeps for 1 second, invokes the executionThread() method, and returns a string value.
  • Line 27: Once completableFuture1 completes, we print the value returned by the Future using the thenAccept() method.
  • Line 28: The main thread sleeps for 2 seconds.

RELATED TAGS

java
communitycreator
thenaccept
completablefuture
RELATED COURSES

View all Courses

Keep Exploring