Java 8 Streams - Timeout?

后端 未结 5 1836
囚心锁ツ
囚心锁ツ 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 09:49

    As what the comments said under the OP, takeWhile/dropWhile are missed in Java 8 (will be added in Java 9). There is no any reason to try to implement the logic by exception or other codes because the code just looks so ugly and total nonscenes even it's just for practice. I think using 3rd party library is a much, much better solution, for example StreamEx

    StreamEx(source).takeWhile(() -> System.currentTimeMillis() <= start + 30000)
                    .forEach(e -> { ... });
    

提交回复
热议问题