How to execute a runnable asynchronously in Java

runAsync() is a staticthe methods in Java that can be called without creating an object of the class. method of the CompletableFuture which is used to execute a runnable asynchronously in a pool of threads.

The runAsync method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class check the following import statement.

import java.util.concurrent.CompletableFuture;

runAsync(Runnable runnable)

This method considers the passed Runnable implementation as a task that will be completed asynchronously. By default, the task will be executed asynchronously in ForkJoinPool.commonPool() and the method returns a new CompletableFuture with no value.

Syntax


public static CompletableFuture<Void> runAsync(Runnable runnable)

Parameters

  • Runnable runnable: The task to execute.

Return value

This method returns a new CompletableFuture.

Code

import java.util.concurrent.*;
public class Main {
private static CompletableFuture<Void> createFuture(){
Runnable runnable = () -> {
sleep(1000);
System.out.println("Hello Educative");
System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());
};
return CompletableFuture.runAsync(runnable);
}
private static void sleep(int millis){
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
createFuture().get();
sleep(3000);
System.out.println("Completed Processing");
}
}

Explanation

  • Line 1: We import the relevant packages and classes.
  • Line 5: We define a function called createFuture() which submits the runnable to the ForkJoinPool.commonPool() and returns a CompletableFuture.
  • Line 6-10: We create a runnable that sleeps for one second and prints a string and the thread executing it.
  • Lines 14-20: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Line 23: We get the CompletableFuture by invoking the createFuture method. Using the get() method, we wait for the future to complete the execution.
  • Line 25: We invoke the sleep function on the main thread.
  • Line 27: We print the string Completed Processing to the console.

Free Resources