Java 8 Streams - Timeout?

后端 未结 5 1832
囚心锁ツ
囚心锁ツ 2021-02-05 09:44

I want to loop over a huge array and do a complicated set of instructions that takes a long time. However, if more than 30 seconds have passed, I want it to give up.

ex.

5条回答
  •  野的像风
    2021-02-05 10:08

    I would create a custom pool for that, something like:

    ForkJoinPool forkJoinPool = new ForkJoinPool(1);
        try {
            forkJoinPool.submit(() ->
            IntStream.range(1, 1_000_000).filter(x -> x > 2).boxed().collect(Collectors.toList()))
                    .get(30, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // job not done in your interval
        }
    

提交回复
热议问题