|
9 | 9 | ---
|
10 | 10 |
|
11 | 11 | ##Intent
|
12 |
| -Asynchronous method invocation is pattern where the calling thread |
| 12 | + |
| 13 | +Asynchronous method invocation is a pattern where the calling thread |
13 | 14 | is not blocked while waiting results of tasks. The pattern provides parallel
|
14 | 15 | processing of multiple independent tasks and retrieving the results via
|
15 | 16 | callbacks or waiting until everything is done.
|
16 | 17 |
|
| 18 | +##Explanation |
| 19 | + |
| 20 | +Real world example |
| 21 | + |
| 22 | +>Launching space rockets is an exciting business. The mission command gives an order to launch and |
| 23 | +>after some undetermined time, the rocket either launches successfully or fails miserably. |
| 24 | +
|
| 25 | +In plain words |
| 26 | + |
| 27 | +>Asynchronous method invocation starts task processing and returns immediately before the task is |
| 28 | +>ready. The results of the task processing are returned to the caller later. |
| 29 | +
|
| 30 | +Wikipedia says |
| 31 | + |
| 32 | +>In multithreaded computer programming, asynchronous method invocation (AMI), also known as |
| 33 | +>asynchronous method calls or the asynchronous pattern is a design pattern in which the call site |
| 34 | +>is not blocked while waiting for the called code to finish. Instead, the calling thread is |
| 35 | +>notified when the reply arrives. Polling for a reply is an undesired option. |
| 36 | +
|
| 37 | +**Programmatic Example** |
| 38 | + |
| 39 | +In this example, we are launching space rockets and deploying lunar rovers. |
| 40 | + |
| 41 | +The application demonstrates the async method invocation pattern. The key parts of the pattern are |
| 42 | +`AsyncResult` which is an intermediate container for an asynchronously evaluated value, |
| 43 | +`AsyncCallback` which can be provided to be executed on task completion and`AsyncExecutor` that |
| 44 | +manages the execution of the async tasks. |
| 45 | + |
| 46 | +```java |
| 47 | +publicinterfaceAsyncResult<T> { |
| 48 | +booleanisCompleted(); |
| 49 | +TgetValue()throwsExecutionException; |
| 50 | +voidawait()throwsInterruptedException; |
| 51 | +} |
| 52 | +``` |
| 53 | + |
| 54 | +```java |
| 55 | +publicinterfaceAsyncCallback<T> { |
| 56 | +voidonComplete(Tvalue,Optional<Exception>ex); |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +```java |
| 61 | +publicinterfaceAsyncExecutor { |
| 62 | +<T>AsyncResult<T>startProcess(Callable<T>task); |
| 63 | +<T>AsyncResult<T>startProcess(Callable<T>task,AsyncCallback<T>callback); |
| 64 | +<T>TendProcess(AsyncResult<T>asyncResult)throwsExecutionException,InterruptedException; |
| 65 | +} |
| 66 | +``` |
| 67 | + |
| 68 | +`ThreadAsyncExecutor` is an implementation of`AsyncExecutor`. Some of its key parts are highlighted |
| 69 | +next. |
| 70 | + |
| 71 | +```java |
| 72 | +publicclassThreadAsyncExecutorimplementsAsyncExecutor { |
| 73 | + |
| 74 | +@Override |
| 75 | +public<T>AsyncResult<T>startProcess(Callable<T>task) { |
| 76 | +return startProcess(task,null); |
| 77 | + } |
| 78 | + |
| 79 | +@Override |
| 80 | +public<T>AsyncResult<T>startProcess(Callable<T>task,AsyncCallback<T>callback) { |
| 81 | +var result=newCompletableResult<>(callback); |
| 82 | +newThread( |
| 83 | + ()-> { |
| 84 | +try { |
| 85 | + result.setValue(task.call()); |
| 86 | + }catch (Exception ex) { |
| 87 | + result.setException(ex); |
| 88 | + } |
| 89 | + }, |
| 90 | +"executor-"+ idx.incrementAndGet()) |
| 91 | + .start(); |
| 92 | +return result; |
| 93 | + } |
| 94 | + |
| 95 | +@Override |
| 96 | +public<T>TendProcess(AsyncResult<T>asyncResult) |
| 97 | +throwsExecutionException,InterruptedException { |
| 98 | +if (!asyncResult.isCompleted()) { |
| 99 | + asyncResult.await(); |
| 100 | + } |
| 101 | +return asyncResult.getValue(); |
| 102 | + } |
| 103 | +} |
| 104 | +``` |
| 105 | + |
| 106 | +Then we are ready to launch some rockets to see how everything works together. |
| 107 | + |
| 108 | +```java |
| 109 | +publicstaticvoid main(String[] args) throwsException { |
| 110 | +// construct a new executor that will run async tasks |
| 111 | +var executor=newThreadAsyncExecutor(); |
| 112 | + |
| 113 | +// start few async tasks with varying processing times, two last with callback handlers |
| 114 | +finalvar asyncResult1= executor.startProcess(lazyval(10,500)); |
| 115 | +finalvar asyncResult2= executor.startProcess(lazyval("test",300)); |
| 116 | +finalvar asyncResult3= executor.startProcess(lazyval(50L,700)); |
| 117 | +finalvar asyncResult4= executor.startProcess(lazyval(20,400), callback("Deploying lunar rover")); |
| 118 | +finalvar asyncResult5= |
| 119 | + executor.startProcess(lazyval("callback",600), callback("Deploying lunar rover")); |
| 120 | + |
| 121 | +// emulate processing in the current thread while async tasks are running in their own threads |
| 122 | +Thread.sleep(350);// Oh boy, we are working hard here |
| 123 | + log("Mission command is sipping coffee"); |
| 124 | + |
| 125 | +// wait for completion of the tasks |
| 126 | +finalvar result1= executor.endProcess(asyncResult1); |
| 127 | +finalvar result2= executor.endProcess(asyncResult2); |
| 128 | +finalvar result3= executor.endProcess(asyncResult3); |
| 129 | + asyncResult4.await(); |
| 130 | + asyncResult5.await(); |
| 131 | + |
| 132 | +// log the results of the tasks, callbacks log immediately when complete |
| 133 | + log("Space rocket <"+ result1+"> launch complete"); |
| 134 | + log("Space rocket <"+ result2+"> launch complete"); |
| 135 | + log("Space rocket <"+ result3+"> launch complete"); |
| 136 | +} |
| 137 | +``` |
| 138 | + |
| 139 | +Here's the program console output. |
| 140 | + |
| 141 | +```java |
| 142 | +21:47:08.227 [executor-2]INFOcom.iluwatar.async.method.invocation.App-Space rocket<test> launched successfully |
| 143 | +21:47:08.269 [main]INFOcom.iluwatar.async.method.invocation.App-Mission command is sipping coffee |
| 144 | +21:47:08.318 [executor-4]INFOcom.iluwatar.async.method.invocation.App-Space rocket<20> launched successfully |
| 145 | +21:47:08.335 [executor-4]INFOcom.iluwatar.async.method.invocation.App-Deploying lunar rover<20> |
| 146 | +21:47:08.414 [executor-1]INFOcom.iluwatar.async.method.invocation.App-Space rocket<10> launched successfully |
| 147 | +21:47:08.519 [executor-5]INFOcom.iluwatar.async.method.invocation.App-Space rocket<callback> launched successfully |
| 148 | +21:47:08.519 [executor-5]INFOcom.iluwatar.async.method.invocation.App-Deploying lunar rover<callback> |
| 149 | +21:47:08.616 [executor-3]INFOcom.iluwatar.async.method.invocation.App-Space rocket<50> launched successfully |
| 150 | +21:47:08.617 [main]INFOcom.iluwatar.async.method.invocation.App-Space rocket<10> launch complete |
| 151 | +21:47:08.617 [main]INFOcom.iluwatar.async.method.invocation.App-Space rocket<test> launch complete |
| 152 | +21:47:08.618 [main]INFOcom.iluwatar.async.method.invocation.App-Space rocket<50> launch complete |
| 153 | +``` |
| 154 | + |
17 | 155 | #Class diagram
|
| 156 | + |
18 | 157 | 
|
19 | 158 |
|
20 | 159 | ##Applicability
|
21 |
| -Use async method invocation pattern when |
| 160 | + |
| 161 | +Use the async method invocation pattern when |
22 | 162 |
|
23 | 163 | * You have multiple independent tasks that can run in parallel
|
24 | 164 | * You need to improve the performance of a group of sequential tasks
|
25 |
| -* You have limited amount of processing capacity or long running tasks and the |
26 |
| - caller should not wait the tasks to be ready |
| 165 | +* You have a limited amount of processing capacity or long-running tasks and the caller should not wait for the tasks to be ready |
27 | 166 |
|
28 | 167 | ##Real world examples
|
29 | 168 |
|
|