refactor: Eliminate Optional from fields and parameters for async method invocation (#2830)

This commit is contained in:
guqing
2024-03-23 18:03:13 +08:00
committed by GitHub
parent 846dea2dca
commit 79dd5a7abc
6 changed files with 53 additions and 47 deletions
@@ -118,12 +118,16 @@ public class App {
* @return new async callback
*/
private static <T> AsyncCallback<T> callback(String name) {
return (value, ex) -> {
if (ex.isPresent()) {
log(name + " failed: " + ex.map(Exception::getMessage).orElse(""));
} else {
return new AsyncCallback<>() {
@Override
public void onComplete(T value) {
log(name + " <" + value + ">");
}
@Override
public void onError(Exception ex) {
log(name + " failed: " + ex.getMessage());
}
};
}
@@ -24,8 +24,6 @@
*/
package com.iluwatar.async.method.invocation;
import java.util.Optional;
/**
* AsyncCallback interface.
*
@@ -34,10 +32,16 @@ import java.util.Optional;
public interface AsyncCallback<T> {
/**
* Complete handler which is executed when async task is completed or fails execution.
* Complete handler which is executed when async task is completed.
*
* @param value the evaluated value from async task, undefined when execution fails
* @param ex empty value if execution succeeds, some exception if executions fails
* @param value the evaluated value from async task
*/
void onComplete(T value, Optional<Exception> ex);
void onComplete(T value);
/**
* Error handler which is executed when async task fails execution.
*
* @param ex exception which was thrown during async task execution(non-null)
*/
void onError(Exception ex);
}
@@ -81,7 +81,7 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
static final int COMPLETED = 3;
final Object lock;
final Optional<AsyncCallback<T>> callback;
final AsyncCallback<T> callback;
volatile int state = RUNNING;
T value;
@@ -89,7 +89,11 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
CompletableResult(AsyncCallback<T> callback) {
this.lock = new Object();
this.callback = Optional.ofNullable(callback);
this.callback = callback;
}
boolean hasCallback() {
return callback != null;
}
/**
@@ -101,7 +105,9 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
void setValue(T value) {
this.value = value;
this.state = COMPLETED;
this.callback.ifPresent(ac -> ac.onComplete(value, Optional.empty()));
if (hasCallback()) {
callback.onComplete(value);
}
synchronized (lock) {
lock.notifyAll();
}
@@ -116,7 +122,9 @@ public class ThreadAsyncExecutor implements AsyncExecutor {
void setException(Exception exception) {
this.exception = exception;
this.state = FAILED;
this.callback.ifPresent(ac -> ac.onComplete(null, Optional.of(exception)));
if (hasCallback()) {
callback.onError(exception);
}
synchronized (lock) {
lock.notifyAll();
}