|
4 | 4 |
|
5 | 5 | /** |
6 | 6 | * This application demonstrates the async method invocation pattern. Key parts of the pattern are |
7 | | - * <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated value, |
8 | | - * <code>AsyncCallback</code> which can be provided to be executed on task completion and |
| 7 | + * <code>AsyncResult</code> which is an intermediate container for an asynchronously evaluated |
| 8 | + * value, <code>AsyncCallback</code> which can be provided to be executed on task completion and |
9 | 9 | * <code>AsyncExecutor</code> that manages the execution of the async tasks. |
10 | 10 | * <p> |
11 | | - * The main method shows example flow of async invocations. The main thread starts multiple tasks with |
12 | | - * variable durations and then continues its own work. When the main thread has done it's job it collects |
13 | | - * the results of the async tasks. Two of the tasks are handled with callbacks, meaning the callbacks are |
14 | | - * executed immediately when the tasks complete. |
| 11 | + * The main method shows example flow of async invocations. The main thread starts multiple tasks |
| 12 | + * with variable durations and then continues its own work. When the main thread has done it's job |
| 13 | + * it collects the results of the async tasks. Two of the tasks are handled with callbacks, meaning |
| 14 | + * the callbacks are executed immediately when the tasks complete. |
15 | 15 | * <p> |
16 | | - * Noteworthy difference of thread usage between the async results and callbacks is that the async results |
17 | | - * are collected in the main thread but the callbacks are executed within the worker threads. This should be |
18 | | - * noted when working with thread pools. |
| 16 | + * Noteworthy difference of thread usage between the async results and callbacks is that the async |
| 17 | + * results are collected in the main thread but the callbacks are executed within the worker |
| 18 | + * threads. This should be noted when working with thread pools. |
19 | 19 | * <p> |
20 | | - * Java provides its own implementations of async method invocation pattern. FutureTask, CompletableFuture |
21 | | - * and ExecutorService are the real world implementations of this pattern. But due to the nature of parallel |
22 | | - * programming, the implementations are not trivial. This example does not take all possible scenarios into |
23 | | - * account but rather provides a simple version that helps to understand the pattern. |
| 20 | + * Java provides its own implementations of async method invocation pattern. FutureTask, |
| 21 | + * CompletableFuture and ExecutorService are the real world implementations of this pattern. But due |
| 22 | + * to the nature of parallel programming, the implementations are not trivial. This example does not |
| 23 | + * take all possible scenarios into account but rather provides a simple version that helps to |
| 24 | + * understand the pattern. |
24 | 25 | * |
25 | 26 | * @see AsyncResult |
26 | 27 | * @see AsyncCallback |
|
32 | 33 | */ |
33 | 34 | public class App { |
34 | 35 |
|
35 | | - public static void main(String[] args) throws Exception { |
36 | | - // construct a new executor that will run async tasks |
37 | | - AsyncExecutor executor = new ThreadAsyncExecutor(); |
| 36 | + public static void main(String[] args) throws Exception { |
| 37 | + // construct a new executor that will run async tasks |
| 38 | + AsyncExecutor executor = new ThreadAsyncExecutor(); |
38 | 39 |
|
39 | | - // start few async tasks with varying processing times, two last with callback handlers |
40 | | - AsyncResult<Integer> asyncResult1 = executor.startProcess(lazyval(10, 500)); |
41 | | - AsyncResult<String> asyncResult2 = executor.startProcess(lazyval("test", 300)); |
42 | | - AsyncResult<Long> asyncResult3 = executor.startProcess(lazyval(50L, 700)); |
43 | | - AsyncResult<Integer> asyncResult4 = executor.startProcess(lazyval(20, 400), callback("Callback result 4")); |
44 | | - AsyncResult<String> asyncResult5 = executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); |
| 40 | + // start few async tasks with varying processing times, two last with callback handlers |
| 41 | + AsyncResult<Integer> asyncResult1 = executor.startProcess(lazyval(10, 500)); |
| 42 | + AsyncResult<String> asyncResult2 = executor.startProcess(lazyval("test", 300)); |
| 43 | + AsyncResult<Long> asyncResult3 = executor.startProcess(lazyval(50L, 700)); |
| 44 | + AsyncResult<Integer> asyncResult4 = |
| 45 | + executor.startProcess(lazyval(20, 400), callback("Callback result 4")); |
| 46 | + AsyncResult<String> asyncResult5 = |
| 47 | + executor.startProcess(lazyval("callback", 600), callback("Callback result 5")); |
45 | 48 |
|
46 | | - // emulate processing in the current thread while async tasks are running in their own threads |
47 | | - Thread.sleep(350); // Oh boy I'm working hard here |
48 | | - log("Some hard work done"); |
| 49 | + // emulate processing in the current thread while async tasks are running in their own threads |
| 50 | + Thread.sleep(350); // Oh boy I'm working hard here |
| 51 | + log("Some hard work done"); |
49 | 52 |
|
50 | | - // wait for completion of the tasks |
51 | | - Integer result1 = executor.endProcess(asyncResult1); |
52 | | - String result2 = executor.endProcess(asyncResult2); |
53 | | - Long result3 = executor.endProcess(asyncResult3); |
54 | | - asyncResult4.await(); |
55 | | - asyncResult5.await(); |
| 53 | + // wait for completion of the tasks |
| 54 | + Integer result1 = executor.endProcess(asyncResult1); |
| 55 | + String result2 = executor.endProcess(asyncResult2); |
| 56 | + Long result3 = executor.endProcess(asyncResult3); |
| 57 | + asyncResult4.await(); |
| 58 | + asyncResult5.await(); |
56 | 59 |
|
57 | | - // log the results of the tasks, callbacks log immediately when complete |
58 | | - log("Result 1: " + result1); |
59 | | - log("Result 2: " + result2); |
60 | | - log("Result 3: " + result3); |
61 | | - } |
| 60 | + // log the results of the tasks, callbacks log immediately when complete |
| 61 | + log("Result 1: " + result1); |
| 62 | + log("Result 2: " + result2); |
| 63 | + log("Result 3: " + result3); |
| 64 | + } |
62 | 65 |
|
63 | | - /** |
64 | | - * Creates a callable that lazily evaluates to given value with artificial delay. |
65 | | - * |
66 | | - * @param value value to evaluate |
67 | | - * @param delayMillis artificial delay in milliseconds |
68 | | - * @return new callable for lazy evaluation |
69 | | - */ |
70 | | - private static <T> Callable<T> lazyval(T value, long delayMillis) { |
71 | | - return () -> { |
72 | | - Thread.sleep(delayMillis); |
73 | | - log("Task completed with: " + value); |
74 | | - return value; |
75 | | - }; |
76 | | - } |
| 66 | + /** |
| 67 | + * Creates a callable that lazily evaluates to given value with artificial delay. |
| 68 | + * |
| 69 | + * @param value value to evaluate |
| 70 | + * @param delayMillis artificial delay in milliseconds |
| 71 | + * @return new callable for lazy evaluation |
| 72 | + */ |
| 73 | + private static <T> Callable<T> lazyval(T value, long delayMillis) { |
| 74 | + return () -> { |
| 75 | + Thread.sleep(delayMillis); |
| 76 | + log("Task completed with: " + value); |
| 77 | + return value; |
| 78 | + }; |
| 79 | + } |
77 | 80 |
|
78 | | - /** |
79 | | - * Creates a simple callback that logs the complete status of the async result. |
80 | | - * |
81 | | - * @param name callback name |
82 | | - * @return new async callback |
83 | | - */ |
84 | | - private static <T> AsyncCallback<T> callback(String name) { |
85 | | - return (value, ex) -> { |
86 | | - if (ex.isPresent()) { |
87 | | - log(name + " failed: " + ex.map(Exception::getMessage).orElse("")); |
88 | | - } else { |
89 | | - log(name + ": " + value); |
90 | | - } |
91 | | - }; |
92 | | - } |
| 81 | + /** |
| 82 | + * Creates a simple callback that logs the complete status of the async result. |
| 83 | + * |
| 84 | + * @param name callback name |
| 85 | + * @return new async callback |
| 86 | + */ |
| 87 | + private static <T> AsyncCallback<T> callback(String name) { |
| 88 | + return (value, ex) -> { |
| 89 | + if (ex.isPresent()) { |
| 90 | + log(name + " failed: " + ex.map(Exception::getMessage).orElse("")); |
| 91 | + } else { |
| 92 | + log(name + ": " + value); |
| 93 | + } |
| 94 | + }; |
| 95 | + } |
93 | 96 |
|
94 | | - private static void log(String msg) { |
95 | | - System.out.println(String.format("[%1$-10s] - %2$s", Thread.currentThread().getName(), msg)); |
96 | | - } |
| 97 | + private static void log(String msg) { |
| 98 | + System.out.println(String.format("[%1$-10s] - %2$s", Thread.currentThread().getName(), msg)); |
| 99 | + } |
97 | 100 | } |
0 commit comments