简体   繁体   English

如何为并行 stream 中的任务抛出超时异常

[英]How to throw Timeout exception for the task inside parallel stream

The code I want to achieve is as below:我想要实现的代码如下:

StreamSupport.stream(jsonArray.spliterator(), true).forEach(s ->{
   try {
       //invoke other api and set timeout for its execution
   }
   catch(TimeoutException e) {
       s.getAsJsonObject().addProperty("processStatus", "Failure");
   }
});

Can anyone help me in achieving "invoke other api and set timeout for it's execution" case in the above snippet?谁能帮我在上面的代码片段中实现“调用其他 api 并为其执行设置超时”的情况?

I don't think you can do that inside a stream, but you can wrap the execution in a Callable like so to achieve the same result:我认为您不能在 stream 中执行此操作,但您可以像这样将执行包装在 Callable 中以实现相同的结果:

  public static void main(String[] args) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());
        try {
            System.out.println(future.get(1, TimeUnit.SECONDS));
        }catch (Exception e) {
            future.cancel(true);
            e.printStackTrace();
        } finally { 
            executor.shutdownNow();
        }
    }

    private static class Task implements Callable<String> {
        @Override
        public String call(){
            IntStream.of(1,2,3,4,5,6,7,8,9).parallel().forEach(t -> {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            return "ok";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM