我怎样才能优雅地序列化lambda?
例如,下面的代码抛出一个NotSerializableException.如何在不创建SerializableRunnable"虚拟"界面的情况下修复它?
public static void main(String[] args) throws Exception {
File file = Files.createTempFile("lambda", "ser").toFile();
try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
Runnable r = () -> System.out.println("Can I be serialized?");
oo.writeObject(r);
}
try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
Runnable r = (Runnable) oi.readObject();
r.run();
}
}
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
// How to throw the ServerException?
public void myFunc() throws ServerException{
// Some code
CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
try {
return someObj.someFunc();
} catch(ServerException ex) {
// throw ex; gives an error here.
}
}));
// Some code
}
Run Code Online (Sandbox Code Playgroud)
someFunc()抛出一个ServerException.我不想在这里处理这个问题,而是将异常抛给someFunc()调用者myFunc().
CompletableFuture.supplyAsync(
() -> {
transporter.write(req);
//here take the value from a blocking queue,will throw a interruptedException
return responseQueue.take();
}, executorService);
Run Code Online (Sandbox Code Playgroud)
处理interruptedException的常用方法是再次中断或直接抛出interruptedException,但两者都无法工作.有人有想法吗?
使用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中的已检查异常?
Stackoverflow 包含多个有关将检查异常与CompletableFuture.
这里有一些例子:
虽然一些答案暗示使用CompletableFuture.completeExceptionally()他们的方法会导致用户代码难以阅读。
我将利用这个空间提供一个替代解决方案,以提高可读性。
请注意,这个问题特定于 CompletableFuture。这使我们能够提供不更普遍地扩展到 lambda 表达式的解决方案。