Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java executor.invokeAll()lambda主体不返回_Java_Multithreading_Return_Void_Executor - Fatal编程技术网

Java executor.invokeAll()lambda主体不返回

Java executor.invokeAll()lambda主体不返回,java,multithreading,return,void,executor,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 call

这个想法是针对某种编译器的,我正在尝试实现一个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());
}
List>callList=lista.stream().map(p->(Callable)()->p.oneStep()).collect(collector.toList())//在这里,我刚刚准备了可调用的列表
列表newPrgs;
试一试{
newPrgs=executor.invokeAll(callList.stream().map(future->{
试一试{
返回future.get();
}捕获(例外e){
e、 printStackTrace();
}
}
/这里它表示错误/.filter(p->p!=null).collect(Collectors.toList());
}捕捉(中断异常e){
抛出新的CustomException(例如getMessage());
}

错误是:lambda body既不与value兼容,也不与void兼容。我尝试了各种更改和技巧,但没有结果。请提供一些帮助?

问题在于lambda的定义

{
    try{
      return future.get();
    }
    catch (Exception e){
      e.printStackTrace();
    }
}
现在,这对于happy path来说很好,它只返回将来的响应,但是如果发生异常,这个lambda将不会返回值。您需要从异常情况返回一些内容,或者抛出RuntimeException。该怎么做取决于您的用例-异常将停止整个流的处理,但是null或默认值可能会污染您的流

另外,通常最好不要捕获异常-将捕获保持在您能够处理的最小必要集

异常引发窗体看起来像

{
    try{
      return future.get();
    }
    catch (InterruptedException | ExecutionException e){
      e.printStackTrace();
      throw new RuntimeException(e)
    }
}

看看你的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方法,也不能转换为具有返回值的方法

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