Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
completablefuture

How to execute runnable in custom pool of threads asynchronously

abhilash

Overview

runAsync() is a staticThe methods in Java that can be called without creating an object of the class. method of the CompletableFuture used to execute a runnable asynchronously in a custom 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 use the following import statement:

import java.util.concurrent.CompletableFuture;

runAsync(Runnable runnable, Executor executor)

This method considers the passed Runnable implementation as a task that is completed asynchronously. The task is executed asynchronously in the passed executor, and the method returns a new CompletableFuture with no value.

Syntax


public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

Parameters

  • Runnable runnable: The task to execute.
  • Executor executor: The executor to run the task asynchronously.

Return value

This method returns a new CompletableFuture.

Code

import java.util.concurrent.*;

public class Main {

    static ExecutorService customExecutorService = Executors.newSingleThreadExecutor();

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

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

        customExecutorService.shutdown();
    }
}
Implementation of the "runAsync()" method

Explanation

  • Line 1: We import the relevant packages and classes.
  • Line 5: We define a single-threaded thread pool called customExecutorService.
  • Line 7: We define a function called createFuture() that submits the runnable to customExecutorService and returns a CompletableFuture.
  • Lines 8 to 12: We create a runnable that sleeps for one second and prints a string and the thread executing it.
  • Line 13: We submit the runnable to the customExecutorService using the runAsync() method.
  • Lines 16 to 22: We define a function called sleep() that makes the current thread sleep for the given amount of milliseconds.
  • Line 25: We get the CompletableFuture by invoking the createFuture method. Using the get() method we wait for the future to complete the execution.
  • Line 27: We invoke the sleep function on the main thread.
  • Line 29: We print the string Completed Processing to the console.
  • Line 31: We shut down the customExecutorService.

RELATED TAGS

java
communitycreator
completablefuture
RELATED COURSES

View all Courses

Keep Exploring