Java 8 Streams - Timeout?

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

    Since Stream forEach doesn't have break, I think you can create Custom Exception for this to break the loop:

    myDataStructure.stream()
        .forEach(e ->
        {
          if (System.currentTimeMillis() <= start + 30000) {
              throw new MyTimeOutException()
          }
        });
    

    and you can catch this Exception for catch this.

提交回复
热议问题