completablefuture usage
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!"
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...
