Skip to content

Commit 16a8c85

Browse files
committed
Reformat Async Method Invocation - Issue iluwatar#224
1 parent 95c1620 commit 16a8c85

File tree

6 files changed

+242
-241
lines changed

6 files changed

+242
-241
lines changed

async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/App.java

Lines changed: 71 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,24 @@
44

55
/**
66
* 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
99
* <code>AsyncExecutor</code> that manages the execution of the async tasks.
1010
* <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.
1515
* <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.
1919
* <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.
2425
*
2526
* @see AsyncResult
2627
* @see AsyncCallback
@@ -32,66 +33,68 @@
3233
*/
3334
public class App {
3435

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();
3839

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"));
4548

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");
4952

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();
5659

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+
}
6265

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+
}
7780

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+
}
9396

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+
}
97100
}

async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncCallback.java

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,11 @@
1111
*/
1212
public interface AsyncCallback<T> {
1313

14-
/**
15-
* Complete handler which is executed when async task is completed or fails execution.
16-
*
17-
* @param value the evaluated value from async task, undefined when execution fails
18-
* @param ex empty value if execution succeeds, some exception if executions fails
19-
*/
20-
void onComplete(T value, Optional<Exception> ex);
21-
14+
/**
15+
* Complete handler which is executed when async task is completed or fails execution.
16+
*
17+
* @param value the evaluated value from async task, undefined when execution fails
18+
* @param ex empty value if execution succeeds, some exception if executions fails
19+
*/
20+
void onComplete(T value, Optional<Exception> ex);
2221
}

async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncExecutor.java

Lines changed: 26 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -10,33 +10,32 @@
1010
*/
1111
public interface AsyncExecutor {
1212

13-
/**
14-
* Starts processing of an async task. Returns immediately with async result.
15-
*
16-
* @param task task to be executed asynchronously
17-
* @return async result for the task
18-
*/
19-
<T> AsyncResult<T> startProcess(Callable<T> task);
13+
/**
14+
* Starts processing of an async task. Returns immediately with async result.
15+
*
16+
* @param task task to be executed asynchronously
17+
* @return async result for the task
18+
*/
19+
<T> AsyncResult<T> startProcess(Callable<T> task);
2020

21-
/**
22-
* Starts processing of an async task. Returns immediately with async result. Executes callback
23-
* when the task is completed.
24-
*
25-
* @param task task to be executed asynchronously
26-
* @param callback callback to be executed on task completion
27-
* @return async result for the task
28-
*/
29-
<T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
30-
31-
/**
32-
* Ends processing of an async task. Blocks the current thread if necessary and returns the
33-
* evaluated value of the completed task.
34-
*
35-
* @param asyncResult async result of a task
36-
* @return evaluated value of the completed task
37-
* @throws ExecutionException if execution has failed, containing the root cause
38-
* @throws InterruptedException if the execution is interrupted
39-
*/
40-
<T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
21+
/**
22+
* Starts processing of an async task. Returns immediately with async result. Executes callback
23+
* when the task is completed.
24+
*
25+
* @param task task to be executed asynchronously
26+
* @param callback callback to be executed on task completion
27+
* @return async result for the task
28+
*/
29+
<T> AsyncResult<T> startProcess(Callable<T> task, AsyncCallback<T> callback);
4130

31+
/**
32+
* Ends processing of an async task. Blocks the current thread if necessary and returns the
33+
* evaluated value of the completed task.
34+
*
35+
* @param asyncResult async result of a task
36+
* @return evaluated value of the completed task
37+
* @throws ExecutionException if execution has failed, containing the root cause
38+
* @throws InterruptedException if the execution is interrupted
39+
*/
40+
<T> T endProcess(AsyncResult<T> asyncResult) throws ExecutionException, InterruptedException;
4241
}

async-method-invocation/src/main/java/com/iluwatar/async/method/invocation/AsyncResult.java

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,26 @@
1010
*/
1111
public interface AsyncResult<T> {
1212

13-
/**
14-
* Status of the async task execution.
15-
*
16-
* @return <code>true</code> if execution is completed or failed
17-
*/
18-
boolean isCompleted();
13+
/**
14+
* Status of the async task execution.
15+
*
16+
* @return <code>true</code> if execution is completed or failed
17+
*/
18+
boolean isCompleted();
1919

20-
/**
21-
* Gets the value of completed async task.
22-
*
23-
* @return evaluated value or throws ExecutionException if execution has failed
24-
* @throws ExecutionException if execution has failed, containing the root cause
25-
* @throws IllegalStateException if execution is not completed
26-
*/
27-
T getValue() throws ExecutionException;
20+
/**
21+
* Gets the value of completed async task.
22+
*
23+
* @return evaluated value or throws ExecutionException if execution has failed
24+
* @throws ExecutionException if execution has failed, containing the root cause
25+
* @throws IllegalStateException if execution is not completed
26+
*/
27+
T getValue() throws ExecutionException;
2828

29-
/**
30-
* Blocks the current thread until the async task is completed.
31-
*
32-
* @throws InterruptedException if the execution is interrupted
33-
*/
34-
void await() throws InterruptedException;
29+
/**
30+
* Blocks the current thread until the async task is completed.
31+
*
32+
* @throws InterruptedException if the execution is interrupted
33+
*/
34+
void await() throws InterruptedException;
3535
}

0 commit comments

Comments
 (0)