In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how Java8 uses CompletableFuture to build asynchronous applications, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Overview
To demonstrate the power of CompletableFuture, create an application called best-price-finder that queries multiple online stores to find the lowest price based on a given product or service.
In the process, you will learn several important skills.
How to provide asynchronous API
How to make your code that uses synchronous API become non-blocking code
Together, we will learn how to use pipelining to merge two successive asynchronous operations into a single asynchronous computing operation. For example, the online store returns the original price of the item you want to buy with a discount code-eventually, to calculate the actual price of the item, you have to access a second remote discount service to query the discount rate corresponding to the discount code.
How to handle the completion event of an asynchronous operation in a responsive manner, and how the best price searcher continuously updates the best recommendations for each item as each item returns its price. Instead of waiting for all stores to return their respective prices (there is a risk that users may encounter a white screen if a store's service is interrupted).
Synchronous API VS Asynchronous API synchronous API
Is another name for a traditional method: you call a method, the caller waits while the callee is running, the callee returns after running, and the caller takes the callee's return value and continues to run.
Even if the caller and the callee are running in different threads, the caller still needs to wait for the callee to finish running, which is called a blocked call.
Asynchronous API
In contrast to synchronous API, asynchronous API returns directly, or at least leaves the rest of its calculation to another thread, which is asynchronous with the caller, until the callee's calculation is complete. This is a non-blocking call.
The thread that performs the rest of the calculation task returns its calculation results to the caller. The way to return is either through the callback function or by the caller to perform a "wait to guide the completion of the calculation" method call.
The trouble of synchronization
To achieve the best price querier application, let's start with the API definition that every store should provide.
First, the store should declare how to return the price based on the specified product name:
Public class Shop {public double getPrice (String product) {/ / TODO}}
The internal implementation of this method queries the store's database, but it is also possible to perform other time-consuming tasks, such as contacting other external services.
Use the delay method to simulate the execution of these long-running methods, simulating the execution of 1s, and the method declaration is as follows.
Public static void delay () {try {Thread.sleep (1000L);} catch (InterruptedException e) {throw new RuntimeException (e);}}
The getPrice method calls the delay method and returns a randomly calculated value
Public double getPrice (String product) {return calculatePrice (product);} private double calculatePrice (String product) {delay (); return random.nextDouble () * product.charAt (0) + product.charAt (1);}
Obviously, when the user of this API (in this case, the best price querier) calls the method, it will still be blocked. Waiting for the synchronization event to complete is unacceptable, especially given that the best price querier repeats this operation for all stores in the network.
Next we'll see how to use synchronous API asynchronously to solve this problem. However, in order to learn how to design asynchronous API, you want to rewrite this code in the way of asynchronous API, pretending that we are still suffering from this difficulty, how to rewrite this code in the way of asynchronous API so that users can access it more smoothly?
Implement Asynchronous API change synchronous method to Asynchronous method
To achieve this, you first need to convert getPrice to a getPriceAsync method and modify its return value:
Public Future getPriceAsync (String product) {...}
As we know, Java 5 introduced the java.util.concurrent.Future interface to represent the result of an asynchronous calculation (that is, the calling thread can continue to run without blocking because the method is called).
This means that Future is a processor with a temporarily unknown value, which can be obtained by calling its get method after the calculation is complete. Because of this design, the getPriceAsync method can be returned immediately, giving the calling thread a chance to perform other valuable computing tasks at the same time.
The new CompletableFuture class provides a large number of methods, giving us the opportunity to easily implement this method in a variety of possible ways, such as the following implementation code
[implementation of getPriceAsync method]
In this code, you create an instance of the CompletableFuture object that represents the asynchronous calculation, which contains the result of the calculation when the calculation is complete.
Next, another thread is created by calling fork to perform the actual price calculation, and a Future instance is returned without waiting for the time-consuming calculation task to finish.
When the requested product price is finally calculated, you can use its complete method to end the operation of the completableFuture object and set the value of the variable.
Obviously, the name of this new version of Future also explains its features. Using the client side of this API, you can call it through the following code.
[use asynchronous API]
We see that in this code, the customer asks the store about the price of a certain item. As a result of business? Asynchronous API is provided, and this call immediately returns a Future object through which the customer can get the price of the product at some point in the future.
In this way, while querying the price of goods, customers can also perform some other tasks, such as querying the prices of goods in other stores, without waiting for the first store to return the requested result.
Finally, if all the meaningful work has been done and all the work to be performed by the customer depends on the commodity price, call the get method of Future. After performing this operation, the customer either gets the value encapsulated in the Future (if the asynchronous task has completed) or blocks until the asynchronous task completes and the expected value can be accessed.
Output
You must have found that the call to the getPriceAsync method returns much earlier than the final price calculation is completed.
It is possible to avoid the risk that the client is blocked. In fact, this is very simple. After the Future execution, you can issue a notification to execute a return defined by the Lambda expression or method reference only when the evaluation result is available.
Adjust the function.
But we're not going to talk about it right now, and now we're going to solve another problem: how to manage it correctly.
Errors that may occur during the execution of asynchronous tasks.
Handling exception error
If there are no surprises, the code we are currently developing works fine. But what if there is an error in the price calculation? Unfortunately, in this case you will get a rather bad result: the exception used to prompt the error will be limited to the current thread trying to calculate the commodity price and will eventually kill that thread, which will cause the client waiting for the result of the get method to be permanently blocked.
The client can use an overloaded version of the get method, which uses a timeout parameter to avoid this. This is a recommended practice, and you should try to add timeout logic to your code to avoid similar problems.
Using this method can at least prevent the program from waiting forever, and when a timeout occurs, the program will be notified that Timeout-Exception has occurred.
However, because of this, you won't have a chance to find out what's going on in the thread that calculates commodity prices that causes such failures.
In order for the client to understand why the store cannot provide the requested price, you need to use the
The completeExceptionally method of CompletableFuture will cause an exception that has a problem within the CompletableFuture.
The code is as follows
[throw an exception in CompletableFuture]
The client will now receive an ExecutionException exception that receives an Exception parameter containing the reason for the failure, that is, the exception originally thrown by the price calculation method.
So, for example, if the method throws a run-time exception "product not available", the client gets an ExecutionException like this:
Java.util.concurrent.ExecutionException: java.lang.RuntimeException: product
Not available at java.util.concurrent.CompletableFuture.get (CompletableFuture.java:2237)
At lambdasinaction.chap11.AsyncShopClient.main (AsyncShopClient.java:14)
... 5 more
Caused by: java.lang.RuntimeException: product not available
At lambdasinaction.chap11.AsyncShop.calculatePrice (AsyncShop.java:36)
At lambdasinaction.chap11.AsyncShop.lambda$getPrice$0 (AsyncShop.java:23)
At lambdasinaction.chap11.AsyncShop$$Lambda$1/24071475.run (Unknown Source)
At java.lang.Thread.run (Thread.java:744)
These are all the contents of the article "how Java8 uses CompletableFuture to build asynchronous applications". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.