ListenableFutureCallback - onFailure 永远不会被调用
ListenableFutureCallback - onFailure is never called
我在玩 'ListenableFutureCallback'。 onSuccess() 工作正常,但永远不会调用 onFailure。下面是一些示例代码。
@Service
public class AsyncClass {
@Async
public ListenableFuture<String> execute(Callable<String> callable) throws Exception {
String str = callable.call();
//To force an exception to occur
str.toString();
return new AsyncResult<>(str);
}
}
public void futureMethod(String str) throws Exception {
AsyncClass asyncClass = new AsyncClass();
ListenableFuture<String> future = asyncClass.execute(() -> {
return str;
});
future.addCallback(new ListenableFutureCallback<Object>() {
@Override
public void onFailure(Throwable ex) {
System.out.println("FAIL");
}
@Override
public void onSuccess(Object result) {
System.out.println("SUCCESS");
}
});
}
onSuccess 正常工作。
futureMethod("test value");
Console: SUCCESS
onFailure 不起作用。
futureMethod(null);
Console: java.lang.NullPointerException: null
您没有使用 listenable futures。您正在执行代码并将结果放在可听的未来。
为了触发 onFailure,您需要 运行 未来的失败代码或完成未来的异常。
例如
Futures.immediateFailedFuture(new RuntimeException("woops"));
通常期望从 ListeningExecutorService
s 中检索可听的期货。 ListenableFuture
,与 CompletableFuture
不同,无法从外部完成。
我在玩 'ListenableFutureCallback'。 onSuccess() 工作正常,但永远不会调用 onFailure。下面是一些示例代码。
@Service
public class AsyncClass {
@Async
public ListenableFuture<String> execute(Callable<String> callable) throws Exception {
String str = callable.call();
//To force an exception to occur
str.toString();
return new AsyncResult<>(str);
}
}
public void futureMethod(String str) throws Exception {
AsyncClass asyncClass = new AsyncClass();
ListenableFuture<String> future = asyncClass.execute(() -> {
return str;
});
future.addCallback(new ListenableFutureCallback<Object>() {
@Override
public void onFailure(Throwable ex) {
System.out.println("FAIL");
}
@Override
public void onSuccess(Object result) {
System.out.println("SUCCESS");
}
});
}
onSuccess 正常工作。
futureMethod("test value");
Console: SUCCESS
onFailure 不起作用。
futureMethod(null);
Console: java.lang.NullPointerException: null
您没有使用 listenable futures。您正在执行代码并将结果放在可听的未来。
为了触发 onFailure,您需要 运行 未来的失败代码或完成未来的异常。
例如
Futures.immediateFailedFuture(new RuntimeException("woops"));
通常期望从 ListeningExecutorService
s 中检索可听的期货。 ListenableFuture
,与 CompletableFuture
不同,无法从外部完成。