In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "analyzing Java8 using factory method supplyAsync to create CompletableFuture". In daily operation, I believe many people have doubts in analyzing Java8 using factory method supplyAsync to create CompletableFuture. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "analyzing Java8 using factory method supplyAsync to create CompletableFuture". Next, please follow the editor to study!
Create a CompletableFuture using the factory method supplyAsync
With the supplyAsync method, you can rewrite the getPriceAsync method with one line of code.
[create a CompletableFuture object using the factory method supplyAsync]
Public Future getPriceAsync (String product) {return CompletableFuture.supplyAsync (()-> calculatePrice (product));}
The supplyAsync method takes a producer (Supplier) as a parameter and returns a CompletableFuture object that reads the return value of the calling producer method when it completes asynchronous execution.
The producer method is run by a thread of execution (Executor) in the ForkJoinPool pool, but you can also use an overloaded version of the supplyAsync method, passing a second parameter to specify a different thread of execution of the producer method.
In general, it is possible to pass optional parameters to the factory method of CompletableFuture, and it is feasible to specify the execution thread of the producer method, and later we will show you how to use the execution thread that suits your application characteristics to improve the performance of the program.
Contrast
The code just now
Public Future getPriceAsync (String product) {return CompletableFuture.supplyAsync (()-> calculatePrice (product));}
The CompletableFuture object returned by the getPriceAsync method and the following code
Public Future getPriceAsync (String product) {CompletableFuture futurePrice = new CompletableFuture (); new Thread (()-> {try {double price = calculatePrice (product); futurePrice.complete (price);} catch (Exception ex) {futurePrice.completeExceptionally (ex);}}) .start () Return futurePrice;}
The hand-created and completed CompletableFuture objects are exactly equivalent, which means that they provide the same error management mechanism, while the former takes a lot of effort to build.
Understanding of CompletableFuture async
The verification code is as follows
ExecutorService executorService = Executors.newFixedThreadPool (3); / / executorService.submit (new RuleTestRunnable (1)); List taskList = new ArrayList (); for (int I = 0; I
< 30; i++) { taskList.add(i); } CompletableFuture a1 = CompletableFuture.supplyAsync(() ->{logger.info ("Thread 1 {} {}", "start"); try {TimeUnit.MILLISECONDS.sleep;} catch (InterruptedException e) {e.printStackTrace ();} logger.info ("Thread 1 {} {}", "end"); return "1" }, executorService); CompletableFuture a2 = CompletableFuture.supplyAsync (()-> {logger.info ("Thread 2 {} {}", "start"); try {TimeUnit.MILLISECONDS.sleep;} catch (InterruptedException e) {e.printStackTrace () } logger.info ("thread 2 {} {}", "end"); return "1";}, executorService); CompletableFuture a = a1.thenCombineAsync (a2, (S1 ~ S2)-> {logger.info ("combined thread {} {}"); return S1 thread 2;}, executorService); Object result = a.get ()
When the executorService thread pool size is 2, the execution result is as follows:
[pool-4-thread-1] INFO test.rcd.thread.CompletableFutureDemo.lambda$mains$4:127-combined threads {} {}
The a1.thenCombineAsync method is always executed by thread 1 or 2
When the executorService thread pool size is 3, the execution result is as follows:
[pool-4-thread-3] INFO test.rcd.thread.CompletableFutureDemo.lambda$mains$4:127-combined threads {} {}
The a1.thenCombineAsync method is always executed by thread 3
Change to a1.thenCombine (), and execute the result:
The a1.thenCombineAsync method is always executed by thread 1 or 2
Thus, the async method always tries to take a new thread execution method, and without the async method, it will fetch thread execution from the current thread. CompletableFuture seems to be thread-independent.
At this point, the study on "analyzing Java8 using factory method supplyAsync to create CompletableFuture" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.