相关疑难解决方法(0)

如何序列化lambda?

我怎样才能优雅地序列化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)

java lambda serialization java-8

152
推荐指数
4
解决办法
4万
查看次数

从CompletableFuture抛出异常

我有以下代码:

// 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().

java exception-handling exception java-8 completable-future

25
推荐指数
2
解决办法
4万
查看次数

JDK8 CompletableFuture.supplyAsync如何处理interruptedException

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 lambda exception java-8

14
推荐指数
2
解决办法
2万
查看次数

使用CompletableFuture检查异常

使用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中的已检查异常?

java asynchronous java-8

7
推荐指数
1
解决办法
5543
查看次数

使用 CompletableFuture 抛出已检查的异常

Stackoverflow 包含多个有关将检查异常与CompletableFuture.

这里有一些例子:

虽然一些答案暗示使用CompletableFuture.completeExceptionally()他们的方法会导致用户代码难以阅读。

我将利用这个空间提供一个替代解决方案,以提高可读性。

请注意,这个问题特定于 CompletableFuture。这使我们能够提供不更普遍地扩展到 lambda 表达式的解决方案。

java completable-future

5
推荐指数
1
解决办法
5028
查看次数