Java 8 Streams - Timeout?

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

    If iterating the stream or array in this case is cheap compared to actually executing the operation than just use a predicate and filter whether time is over or not.

    final long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(30L);
    myDataStructure.stream()
        .filter(e -> System.nanoTime() <= end)
        .forEach(e ->
        {
          ...
        });
    

    Question is if you need to know which elements have been processed or not. With the above you have to inspect whether a side effect took place for a specific element afterwards.

提交回复
热议问题