Java 8 Streams - Timeout?

Viewed 6706

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.

final long start = System.currentTimeMillis();
myDataStructure.stream()
    .while(() -> System.currentTimeMillis() <= start + 30000)
    .forEach(e ->
    {
      ...
    });

I want to avoid just saying return inside the forEach call if a certain condition is met.

5 Answers
Related