0

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?

shmosel
  • 49,289
  • 6
  • 73
  • 138
Usman Mohammed
  • 109
  • 1
  • 9
  • Please read [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – Mark Rotteveel Nov 11 '22 at 17:05

1 Answers1

0

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";
        }
    }
Teddy Tsai
  • 414
  • 1
  • 13