Java 8 Streams - 超时? [英] Java 8 Streams - Timeout?
问题描述
我想循环一个庞大的数组并执行一系列复杂的指令,这需要很长时间。但是,如果超过30秒,我希望它放弃。
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.
前。
final long start = System.currentTimeMillis();
myDataStructure.stream()
.while(() -> System.currentTimeMillis() <= start + 30000)
.forEach(e ->
{
...
});
我想避免在里面说返回
如果满足某个条件,则 forEach
调用。
I want to avoid just saying return
inside the forEach
call if a certain condition is met.
推荐答案
如果迭代与实际执行操作相比,这种情况下的流或数组比使用谓词更便宜,并且过滤时间是否结束。
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.
这篇关于Java 8 Streams - 超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!