Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
completablefuture
communitycreator

What is CompletableFuture.thenRun() in Java?

abhilash

thenRun() is an instance method of the CompletableFuture. It executes a runnable once the CompletableFuture is in the completed stage. It has no access to the result of the CompletableFuture to which it is attached.

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

import java.util.concurrent.CompletableFuture;

Syntax


public CompletableFuture<Void> thenRun(Runnable action)

Parameters

  • Runnable action: It is the runnable action to be run.

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;
        });

        Runnable runnable = () -> System.out.println("Runnable executed");

        completableFuture1.thenAccept(System.out::println).thenRun(runnable);
        sleep(2000);
    }
}
Implementation of the "thenRun" method

Explanation

  • Line 1: We import the relevant packages and classes.
  • Lines 5 to 11: We define a function called sleep(), which makes the current thread sleep for the given amount of milliseconds.
  • Lines 13 to 15: We define a function called executionThread(), which prints the current thread of execution.
  • Lines 19 to 25: We create a completable future called completableFuture1 using the supplyAsyc() method. We do this by passing a supplier that sleeps for 1 second, invokes the executionThread() method, and returns a string value.
  • Line 27: We define a runnable to execute after the completion of completableFuture1.
  • Line 29: Once completableFuture1 is complete, we print the value returned by the future using the thenAccept() method. Then, the runnable is executed.
  • Line 30: The main thread sleeps for 2 seconds.

RELATED TAGS

java
completablefuture
communitycreator
RELATED COURSES

View all Courses

Keep Exploring