Java 8 Streams - Timeout?

后端 未结 5 1837
囚心锁ツ
囚心锁ツ 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:04

    You can use the fact that .allMatch() is a short-circuiting operator to terminate the stream:

    final long start = System.currentTimeMillis();
    myDataStructure.stream()
        .allMatch(e ->
        {
          // your task here
            return System.currentTimeMillis() <= start + 30000;
        });
    

提交回复
热议问题