Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of Java8 customizing CompletableFuture?

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what is the principle of Java8 custom CompletableFuture". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "what is the principle of Java8 custom CompletableFuture"!

Java8 self-defined CompletableFuture principle

The Future interface has many limitations, one of which is to actively ask if it is completed. Wouldn't it be better to let me know when the task of the child thread is finished?

Public class FutureInAction3 {public static void main (String [] args) {Future future = invoke (()-> {try {Thread.sleep (10000L); return "I am Finished.";} catch (InterruptedException e) {return "I am Error";}}) Future.setCompletable (new Completable () {@ Override public void complete (String s) {System.out.println ("complete called -" + s);} @ Override public void exception (Throwable cause) {System.out.println ("error"); cause.printStackTrace () }}); System.out.println (".... do something else."); System.out.println ("try to get result->" + future.get ());} private static Future invoke (Callable callable) {AtomicReference result = new AtomicReference (); AtomicBoolean finished = new AtomicBoolean (false); Future future = new Future () {private Completable completable @ Override public T get () {return result.get ();} @ Override public boolean isDone () {return finished.get () } / / setup completed @ Override public void setCompletable (Completable completable) {this.completable = completable;} / / get @ Override public Completable getCompletable () {return completable;}} Thread t = new Thread (()-> {try {T value = callable.action (); result.set (value); finished.set (true); if (future.getCompletable ()! = null) future.getCompletable () .complete (value) } catch (Throwable cause) {if (future.getCompletable ()! = null) future.getCompletable (). Exception (cause);}}); t.start (); return future;} private interface Future {T get (); boolean isDone (); / / 1 void setCompletable (Completable completable) / / 2 Completable getCompletable ();} private interface Callable {T action ();} / / callback interface private interface Completable {void complete (T t); void exception (Throwable cause);}}

CompleteFuture is easy to use

CompleteFuture in Java8 is an extension of Future, mainly to make up for the lack of corresponding callback mechanism in Future.

Let's first look at the use of Future before Java8

Package demos;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * @ author djh on 10:23 on 2019-4-22 * @ E-Mail 1544579459@qq.com * / public class Demo {public static void main (String [] args) throws ExecutionException, InterruptedException {ExecutorService cachePool = Executors.newCachedThreadPool () Future future = cachePool.submit (()-> {Thread.sleep (3000); return "Asynchronous Task calculation result!";}); / / after the asynchronous task is submitted, the main thread can continue to do some other things. DoSomeThingElse (); / / in order to get the asynchronous calculation result, we can get it through future.get and polling mechanism. The String result; / / Get mode will cause the current thread to block, which obviously violates the original intention of asynchronous computing. / / result = future.get (); / / polling will not cause the current thread to block, but it will cause a high CPU load. Long start = System.currentTimeMillis (); while (true) {if (future.isDone ()) {break;}} System.out.println ("polling time:" + (System.currentTimeMillis ()-start)); result = future.get (); System.out.println ("get asynchronous calculation result:" + result) CachePool.shutdown ();} private static void doSomeThingElse () {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();} System.out.println ("my most important thing is done, I'm going to get the asynchronous calculation results to do the rest.");}}

Output:

My most important thing is done, and I want to get the results of the asynchronous calculation to do the rest.

Polling time: 2000

Get the asynchronous calculation result: the asynchronous task calculation result!

Process finished with exit code 0

From the above Demo, we can see that when future performs asynchronous tasks, the acquisition of results is not so elegant. Many third-party libraries provide callback interfaces for Future to obtain asynchronous computing results, such as Google's: ListenableFuture, and the CompleteFuture provided by Java8 is the official API to make up for this deficiency.

The following is a brief introduction to the use of package demos;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @ author djh on 20:26 * @ E-Mail 1544579459@qq.com * / public class CompleteFutureDemo {public static void main (String [] args) throws ExecutionException, InterruptedException {CompletableFuture completableFutureOne = new CompletableFuture (); ExecutorService cachePool = Executors.newCachedThreadPool () CachePool.execute (()-> {try {Thread.sleep (3000); completableFutureOne.complete ("Asynchronous Task execution result"); System.out.println (Thread.currentThread (). GetName ());} catch (InterruptedException e) {e.printStackTrace ();}}) The CompletableFuture returned by the / / WhenComplete method is still the original CompletableFuture calculation result. CompletableFuture completableFutureTwo = completableFutureOne.whenComplete ((s, throwable)-> {System.out.println ("print the execution result of the asynchronous task when the asynchronous task is finished:" + s);}); / / the ThenApply method returns a new completeFuture. CompletableFuture completableFutureThree = completableFutureTwo.thenApply (s-> {System.out.println ("when the execution of the asynchronous task ends, continue to start a new asynchronous task based on the result of the previous asynchronous task!"); try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace () } return s.length ();}); System.out.println ("blocking method to get execution result:" + completableFutureThree.get ()); cachePool.shutdown ();}}

From the above Demo, we mainly need to pay attention to the two methods thenApply and whenComplete, which are the most meaningful methods in CompleteFuture. They will be called back when completeFuture calls the complete method to pass in the asynchronous calculation result, so as to get the result of the asynchronous task.

Compared with the blocking and polling methods of future to obtain the calculation results of asynchronous tasks, the way of CompleteFuture to obtain the results is much more elegant.

At this point, I believe you have a deeper understanding of "what is the principle of Java8 custom CompletableFuture". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report