a shot of dev knowledge

RELATED TAGS

What is CompletableFuture.getNumberOfDependents() in Java?

The getNumberOfDependents method is an instance method that is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. This method is used to return the number of CompleteFutures that are dependent on the completion of the current CompleteFuture.

To import the CompletableFuture class, we check the following import statement:

import java.util.concurrent.CompletableFuture;

Syntax


public int getNumberOfDependents()

Parameters

This method has no parameters.

Return value

This method returns the number of dependent CompletableFutures.

Code

import java.util.concurrent.*;

public class Main {

    public static void main(String[] args) {

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

        completableFuture.thenApply(i -> i + 1);
        completableFuture.thenApply(i -> i - 1);

        System.out.println("Number of dependents - " + completableFuture.getNumberOfDependents());

        completableFuture.thenApply(i -> i + 2);

        System.out.println("Number of dependents - " + completableFuture.getNumberOfDependents());
    }
}
Implementation of the getNumberOfDependents() method

Code explanation

  • Line 1: We import the relevant classes.
  • Line 7: We create a new CompletableFuture object called completableFuture.
  • Lines 9–10: We chain new stages to the future, using the thenApply method.
  • Line 12: We print the number of dependent futures/stages that are added to the completableFuture future.
  • Line 14: We add one more stage to the future, using the thenApply method.
  • Line 16: We print the number of dependent futures/stages that are added to the completableFuture future.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring