Yol*_*nda 7 java asynchronous java-8
使用Java 8很棒的功能CompletableFuture,我想使用此新功能的例外来转换旧的异步代码.但是经过检查的例外令我困扰.这是我的代码.
CompletableFuture<Void> asyncTaskCompletableFuture =
CompletableFuture.supplyAsync(t -> processor.process(taskParam));
Run Code Online (Sandbox Code Playgroud)
process方法签名:
public void process(Message msg) throws MyException;
Run Code Online (Sandbox Code Playgroud)
如何处理ComletableFuture中的已检查异常?
我尝试过这种方式,但不知道是否是解决问题的好方法。
@FunctionalInterface
public interface RiskEngineFuncMessageProcessor<Void> extends Supplier<Void> {
@Override
default Void get() {
try {
return acceptThrows();
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
Void acceptThrows() throws Exception;
Run Code Online (Sandbox Code Playgroud)
使用Supplier的FunctionalInterface,我可以包装异常:
final MyFuncProcessor<Void> func = () -> {
processor.process(taskParam);
return null;
};
CompletableFuture<Void> asyncTaskCompletableFuture =
CompletableFuture.supplyAsync(func)
.thenAccept(act -> {
finishTask();
})
.exceptionally(exp -> {
log.error("Failed to consume task", exp);
failTask( exp.getMessage());
return null;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5543 次 |
| 最近记录: |