In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what is the use of CompletableFuture in java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The use of CompletableFuture in java
CompletableFuture is first of all a Future, which has all the functions of Future, including getting the result of asynchronous execution, canceling the task being executed, and so on.
In addition, CompletableFuture is also a CompletionStage.
Let's look at the definition of CompletableFuture:
Public class CompletableFuture implements Future, CompletionStage
What is CompletionStage?
In asynchronous programs, it is usually difficult to control the order in which asynchronous programs are executed if each asynchronous execution is treated as a stage. In javascript, we need to execute callbacks in callbacks. This will form the legendary callback hell.
Fortunately, the concept of promise is introduced in ES6, which can convert callbacks in callbacks into chained calls, thus greatly improving the readability and writability of the program.
Similarly in java, we use CompletionStage to implement chain operations for asynchronous calls.
CompletionStage defines a series of then*** operations to implement this function.
CompletableFuture is used as a Future
Calling the CompletableFuture.complete method returns the result immediately. Let's take a look at how to use this method to build a basic Future:
Public Future calculateAsync () throws InterruptedException {CompletableFuture completableFuture= new CompletableFuture (); Executors.newCachedThreadPool (). Submit (()-> {Thread.sleep; completableFuture.complete ("Hello"); return null;}); return completableFuture;}
Above we get a Future by transferring ExecutorService to submit a task. If you know the result of the execution, you can use the completedFuture method of CompletableFuture to return a Future directly.
Public Future useCompletableFuture () {Future completableFuture = CompletableFuture.completedFuture ("Hello"); return completableFuture;}
CompletableFuture also provides a cancel method to cancel the execution of the task immediately:
Public Future calculateAsyncWithCancellation () throws InterruptedException {CompletableFuture completableFuture = new CompletableFuture (); Executors.newCachedThreadPool (). Submit (()-> {Thread.sleep (500); completableFuture.cancel (false); return null;}); return completableFuture;}
If the get method of Future is called at this time, a CancellationException exception will be reported.
Future future = calculateAsyncWithCancellation (); future.get (); / / CancellationException
Execute code asynchronously
CompletableFuture provides methods for runAsync and supplyAsync to execute code asynchronously.
Let's look at a basic application of runAsync and receive a Runnable parameter:
Public void runAsync () {CompletableFuture runAsync= CompletableFuture.runAsync (()-> {log.info ("runAsync");});}
And supplyAsync accepts a Supplier:
Public void supplyAsync () {CompletableFuture supplyAsync=CompletableFuture.supplyAsync (()-> {return "supplyAsync";});}
The difference between the two of them is that one has no return value and the other has a return value.
Combined Futures
One of the important functions of CompletableFuture mentioned above is to change callbacks to chained calls, thus combining Futures.
The return value of the chained call is still CompletableFuture. Let's look at an example of thenCompose:
CompletableFuture completableFuture
= CompletableFuture.supplyAsync (()-> "Hello") .thenCompose (s-> CompletableFuture.supplyAsync (()-> s + "World"))
ThenCompose takes the return result of the previous Future as input to the latter operation.
If we want to merge the results of two CompletableFuture, we can use thenCombine:
Public void thenCombine () {CompletableFuture completableFuture= CompletableFuture.supplyAsync (()-> "Hello") .thenCombine (CompletableFuture.supplyAsync (()-> "World"), (S1, S2)-> S1 + S2);}
If you don't want to return the results, you can use thenAcceptBoth:
Public void thenAcceptBoth () {CompletableFuture future = CompletableFuture.supplyAsync (()-> "Hello") .thenAcceptBoth (CompletableFuture.supplyAsync (()-> "World"), (S1, S2)-> System.out.println (S1 + S2);}
The difference between thenApply () and thenCompose ()
Both the thenApply () and thenCompose () methods can concatenate the CompletableFuture, but the two are a little different.
ThenApply () receives the result returned by the previous call and then processes the result.
ThenCompose () receives the stage of the previous call and returns the CompletableFuture after flat.
In a simple comparison, the two are like the difference between map and flatMap.
Execute tasks in parallel
When we need to execute tasks in parallel, we usually need to wait for all the tasks to be executed before dealing with other tasks, so we can use the CompletableFuture.allOf method:
Public void allOf () {CompletableFuture future1= CompletableFuture.supplyAsync (()-> "Hello"); CompletableFuture future2= CompletableFuture.supplyAsync (()-> "Beautiful"); CompletableFuture future3= CompletableFuture.supplyAsync (()-> "World"); CompletableFuture combinedFuture= CompletableFuture.allOf (future1, future2, future3);}
AllOf only ensures that all task is executed, and there is no return value. If you want to have a return value, we can use join:
Public void join () {CompletableFuture future1= CompletableFuture.supplyAsync (()-> "Hello"); CompletableFuture future2= CompletableFuture.supplyAsync (()-> "Beautiful"); CompletableFuture future3= CompletableFuture.supplyAsync (()-> "World"); String combined = Stream.of (future1, future2, future3) .map (CompletableFuture::join) .map (Collectors.joining ("));}
The above program will return: "Hello Beautiful World".
Exception handling
If you throw an exception during a chained call, you can use handle to receive it at the end:
The trend of house prices in Beihai http://house.bh.goufang.com/lpfangjia/
Public void handleError () {String name = null;CompletableFuture completableFuture= CompletableFuture.supplyAsync (()-> {if (name = = null) {throw new RuntimeException ("Computation error!");} return "Hello,"+ name;}). Handle ((s, t)-> s! = null? S: "Hello, Stranger!");}
This is similar to the use of the catch method in Promise.
This is the end of the content of "what is the use of CompletableFuture in java". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.