Skip to content

Refactor Task execution to support asynchronous callbacks #3274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion callback/src/main/java/com/iluwatar/callback/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ public final class App {
private App() {}

/** Program entry point. */
public static void main(final String[] args) {
public static void main(final String[] args) throws InterruptedException {
var task = new SimpleTask();
task.executeWith(() -> LOGGER.info("I'm done now."));
Thread.sleep(3000);
}
}
12 changes: 8 additions & 4 deletions callback/src/main/java/com/iluwatar/callback/Task.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,19 @@
*/
package com.iluwatar.callback;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;

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

/** Execute with callback. */
/** Execute the task and asynchronously call the callback method upon completion.*/
final void executeWith(Callback callback) {
execute();
Optional.ofNullable(callback).ifPresent(Callback::call);
CompletableFuture.runAsync(() -> {
execute();
if (callback != null) {
callback.call();
}
});
}

public abstract void execute();
Expand Down
Loading