executor.invokeAll()lambda body不返回

时间:2015-12-27 17:51:17

标签: java multithreading return void executor

这个想法适用于某种编译器,我正在尝试实现一个启动另一个线程的fork语句。 代码:

List < Callable < CustomClass >> callList = lista.stream().map(p -> (Callable < CustomClass > )() -> p.oneStep()).collect(Collectors.toList()); //here I just prepared the list of callables
List < CustomClass > newPrgs;
try {
    newPrgs = executor.invokeAll(callList).stream().map(future -> {
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /here it indicates the error/.filter(p -> p != null).collect(Collectors.toList());
} catch (InterruptedException e) {
    throw new CustomException(e.getMessage());
}

错误是:lambda body既不是值也不是void兼容。我尝试了各种变化和技巧,没有结果。有些帮忙吗?

2 个答案:

答案 0 :(得分:1)

问题在于你的lambda的定义......

ptr

现在,这对于快乐路径来说很好,它只返回未来的响应,但是如果发生异常,这个lambda将不会返回值。您需要从异常情况返回一些内容,或者抛出RuntimeException。要做什么取决于您的用例 - 异常将阻止整个流处理,但null或默认值可能会污染您的流。

此外,通常最好不要捕获异常 - 将捕获量保持在您可以处理的最小集合之下。

抛出异常的表格看起来像......

{
    try{
      return future.get();
    }
    catch (Exception e){
      e.printStackTrace();
    }
}

答案 1 :(得分:1)

看看你的lambda的身体:

try {
    return future.get();   // This branch returns a value
} catch (Exception e) {
    e.printStackTrace(); // No return statement here
}
// No return statement here either

因此,您的lambda既不能转换为void方法,也不能转换为具有返回值的方法。

你应该在lambda体的catch或末尾有一个返回值。

相关问题