How to use CompletableFuture to wait for multiple async operations to complete?
CompletableFuture provides a method called allOf
that can be used to wait for multiple asynchronous operations to complete. The allOf
method takes a variable number of CompletableFuture
objects as arguments and returns a new CompletableFuture
that completes when all of the input CompletableFuture
objects have completed.allOf
that can be used to wait for multiple asynchronous operations to complete. The allOf
method takes a variable number of CompletableFuture
objects as arguments and returns a new CompletableFuture
that completes when all of the input CompletableFuture
objects have completed.
The following code sample shows how to use the allOf
method to wait for multiple asynchronous operations to complete:
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World"); CompletableFuture<Void> allOf = CompletableFuture.allOf(future1, future2); allOf.join(); System.out.println(future1.get()); // Prints "Hello" System.out.println(future2.get()); // Prints "World"
How does CompletableFuture's cancellation mechanism work?
CompletableFuture provides a cancel
method that can be used to cancel the asynchronous operation represented by the CompletableFuture
. The cancel
method takes a boolean argument that indicates whether or not the cancellation should be interrupting.
If the cancel
method is called with the interrupting flag set to true
, the asynchronous operation will be interrupted if it is still running. If the asynchronous operation has already completed, the cancel
method will have no effect.
If the cancel
method is called with the interrupting flag set to false
, the asynchronous operation will be cancelled if it has not yet completed. If the asynchronous operation has already completed, the cancel
method will have no effect.
The following code sample shows how to use the cancel
method to cancel an asynchronous operation:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "Hello World"; }); future.cancel(true); // Interrupt the asynchronous operation if (future.isCancelled()) { System.out.println("The asynchronous operation was cancelled."); }
How to handle exceptions and return values with CompletableFuture?
CompletableFuture provides methods for handling both exceptions and return values. The thenApply
and thenAccept
methods can be used to handle return values, while the exceptionally
and handle
methods can be used to handle exceptions.
The thenApply
method takes a function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the function to the result of the original CompletableFuture
. The following code sample shows how to use the thenApply
method to handle a return value:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World"); CompletableFuture<Integer> future2 = future.thenApply(s -> s.length()); future2.join(); System.out.println(future2.get()); // Prints 11
The thenAccept
method takes a consumer as an argument and returns a new CompletableFuture
that will be completed when the consumer has been applied to the result of the original CompletableFuture
. The following code sample shows how to use the thenAccept
method to handle a return value:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello World"); CompletableFuture<Void> future2 = future.thenAccept(s -> System.out.println(s)); future2.join(); // Prints "Hello World"
The exceptionally
method takes a function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the function to the exception that caused the original CompletableFuture
to complete exceptionally. The following code sample shows how to use the exceptionally
method to handle an exception:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { throw new RuntimeException("Error!"); }); CompletableFuture<String> future2 = future.exceptionally(e -> "Error occurred: " + e.getMessage()); future2.join(); System.out.println(future2.get()); // Prints "Error occurred: java.lang.RuntimeException: Error!"
The handle
method takes a bi-function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the bi-function to the result of the original CompletableFuture
and the exception that caused the original CompletableFuture
to complete exceptionally (if any). The following code sample shows how to use the handle
allOf
method to wait for multiple asynchronous operations to complete:🎜CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { if (Math.random() > 0.5) { return "Success"; } else { throw new RuntimeException("Error!"); } }); CompletableFuture<String> future2 = future.handle((result, exception) -> { if (exception != null) { return "Error occurred: " + exception.getMessage(); } else { return result; } }); future2.join(); System.out.println(future2.get()); // Prints "Success" or "Error occurred: java.lang.RuntimeException: Error!"🎜How does CompletableFuture's cancellation mechanism work?🎜🎜CompletableFuture provides a
cancel
method that can be used to cancel the asynchronous operation represented by the CompletableFuture
. The cancel
method takes a boolean argument that indicates whether or not the cancellation should be interrupting.🎜🎜If the cancel
method is called with the interrupting flag set to true
, the asynchronous operation will be interrupted if it is still running. If the asynchronous operation has already completed, the cancel
method will have no effect.🎜🎜If the cancel
method is called with the interrupting flag set to false
, the asynchronous operation will be cancelled if it has not yet completed. If the asynchronous operation has already completed, the cancel
method will have no effect.🎜🎜The following code sample shows how to use the cancel
method to cancel an asynchronous operation:🎜rrreee🎜How to handle exceptions and return values with CompletableFuture?🎜🎜CompletableFuture provides methods for handling both exceptions and return values. The thenApply
and thenAccept
methods can be used to handle return values, while the exceptionally
and handle
methods can be used to handle exceptions.🎜🎜The thenApply
method takes a function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the function to the result of the original CompletableFuture
. The following code sample shows how to use the thenApply
method to handle a return value:🎜rrreee🎜The thenAccept
method takes a consumer as an argument and returns a new CompletableFuture
that will be completed when the consumer has been applied to the result of the original CompletableFuture
. The following code sample shows how to use the thenAccept
method to handle a return value:🎜rrreee🎜The exceptionally
method takes a function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the function to the exception that caused the original CompletableFuture
to complete exceptionally. The following code sample shows how to use the exceptionally
method to handle an exception:🎜rrreee🎜The handle
method takes a bi-function as an argument and returns a new CompletableFuture
that will be completed with the result of applying the bi-function to the result of the original CompletableFuture
and the exception that caused the original CompletableFuture
to complete exceptionally (if any). The following code sample shows how to use the handle
method to handle a return value or an exception:🎜rrreeeThe above is the detailed content of completablefuture usage. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools
