A scenario will be encountered in the development, as follows
Object result1 = service1.func1();//Implementation 80 ms Object result2 =service2.func2();//Implementation 50 ms service3.func3(result1,result2);
func3() needs to wait for func1 and func2 to execute. If func1 and func2 can be executed at the same time, the minimum waiting time will be 50ms
Let's use completable future.
JDK 1.8 is a newly added implementation class completabilfuture, which implements two interfaces: future < T > and completionstage < T >.
Define task class
Here, we define a method find u ser, whose return value is completabilefuture < string > to simulate a remote call.
When the execution result is normal, pass
public boolean complete(T value)
Returns the result.
When an exception is executed, if you want to return an exception to the caller, use the
public boolean completeExceptionally(Throwable ex)
Return exception.
class TaskService{ public CompletableFuture<String> findUser(){ CompletableFuture<String> future = new CompletableFuture(); //Impersonate remote calling thread new Thread(){ @Override public void run() { String result = null; System.out.println("Task start...."); try{ Thread.sleep(3000); //imitate RPC Remote call result = rpcRequest(true); System.out.println("End of task execution...."); } catch(Exception ex){ future.completeExceptionally(ex); } future.complete(result); } }.start(); //Directly return to future return future; } /** *Function description * @author lgj * @Description Impersonate RPC remote call * @date 4/29/19 * @param: flag true: Return normal result false: throw exception * * @return: * */ public String rpcRequest(boolean flag){ String result = null; if(flag){ result = "libai"; } else { throw new NullPointerException(); } return result; } }
Main thread call
public class CompletableFutureDemo { public static void main(String args[]){ TaskService service = new TaskService(); CompletableFuture<String> future = service.findUser(); future.whenComplete((t,u)->{ if(u != null){ System.out.println("Exception in asynchronous call:" + u); } else { System.out.println("Asynchronous call executed normally: " + t); } }); System.out.println("Main thread task completed"); } }
The main thread calls back the result through whenComplete. Here we need to get the result through lambda expression
public CompletableFuture<T> whenComplete( BiConsumer<? super T, ? super Throwable> action) { return uniWhenCompleteStage(null, action); }
When the result is normal
Task start execution Main thread task completed End of task execution Asynchronous call executed normally: libai
When an exception occurs in the call
Task start execution Main thread task completed Exception in asynchronous call: java.lang.NullPointerException
Above, asynchronous call is realized.
At present, dubbo-2.7.0+ It is to use completable future to implement rpc asynchronous call.