How to throw Timeout exception for the task inside parallel stream

320 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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:

  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";
        }
    }