Skip to content

Commit 5d157d6

Browse files
committed
refactor: Refactor Task execution to support asynchronous callbacks
1 parent 3ac1a36 commit 5d157d6

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

callback/src/main/java/com/iluwatar/callback/App.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,9 @@ public final class App {
3737
private App() {}
3838

3939
/** Program entry point. */
40-
public static void main(final String[] args) {
40+
public static void main(final String[] args) throws InterruptedException {
4141
var task = new SimpleTask();
4242
task.executeWith(() -> LOGGER.info("I'm done now."));
43+
Thread.sleep(3000);
4344
}
4445
}

callback/src/main/java/com/iluwatar/callback/Task.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,15 +24,19 @@
2424
*/
2525
package com.iluwatar.callback;
2626

27-
import java.util.Optional;
27+
import java.util.concurrent.CompletableFuture;
2828

2929
/** Template-method class for callback hook execution. */
3030
public abstract class Task {
3131

32-
/** Execute with callback. */
32+
/** Execute the task and asynchronously call the callback method upon completion.*/
3333
final void executeWith(Callback callback) {
34-
execute();
35-
Optional.ofNullable(callback).ifPresent(Callback::call);
34+
CompletableFuture.runAsync(() -> {
35+
execute();
36+
if (callback != null) {
37+
callback.call();
38+
}
39+
});
3640
}
3741

3842
public abstract void execute();

0 commit comments

Comments
 (0)