java - 在异步执行时停止函数链执行的最佳实践是什么?

标签 java java-8

我这里有这个功能:

Function<Integer, Integer> func = (value) -> value + 5;
        func = func.andThen((value) -> {
            //Imagine that here some code executed and raised an exception, I'm throwing it 
            //manually just for the sake of this example.
            throw new RuntimeException("failed");
        });
        func = func.andThen((value) -> {
            System.out.println("Reached last function !");
            return value;
        });
        executeFunction(func);

现在,您可以看到我在第一个 andThen 方法中引发了运行时异常。那是因为我想阻止第二个 andThen 被执行。这是最好的方法吗?

此外,我注意到,如果我在不同的线程(异步)内执行此函数,则异常不会打印在我的控制台中,并且我想知道异常是否发生。

private static void executeFunction(Function<Integer, Integer> function) {
        CompletableFuture.supplyAsync(() -> function.apply(100));
    }

在这种情况下,如果我想确保记录异常,但 andThen 链中的下一个函数没有执行,我应该记录并抛出异常吗?这不是一个 ati 模式吗?

最佳答案

实例化和抛出大量异常可能会变得相当昂贵,这就是为什么它们应该仅限于异常情况。相反,您可以使用 Optional对于控制流:

func = (value) -> Optional.of(value + 5);
func = func.andThen((optionalValue) -> {
    // Instead of throwing an exception, return an empty Optional
    System.out.println("Log the failure");
    return Optional.empty();
});
func = func.andThen((optionalValue) -> {
    optionalValue.map((value) -> { // This lambda will only execute if optionalValue is not empty
        System.out.println("Reached last function !");
        return value; // map wraps this in an Optional
    });
});
// Finally, unwrap the value. Optional provides a number of ways to do this, depending on how you want to handle failure/empty
func = func.andThen((optional) -> optional.orElse(...));
executeFunction(func);

关于java - 在异步执行时停止函数链执行的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58099672/

相关文章:

jpa - Java 8 Spring Data JPA 参数绑定(bind)

java - 如何整齐地对齐字符串变量的输出?

java - 如何使用 jersey 客户端使用 https RestFul Webservice

java - 为什么 parallelStream 不使用整个可用的并行性?

java - 以不同模式运行应用程序

java - 如何使用箭头符号(->)创建 protected 方法?

java - 使用 Java 将文本从一个文件反转并存储到另一个文件时减小大小

java - 二进制随机数

java - 如何将节点值设置为 Bean 并添加到 Beans ArrayList

java - 为什么 Java 8's functional-style constructs called "流”?