我想循环遍历一个巨大的数组,并执行一组复杂的指令,这需要很长时间。但是,如果超过30秒,我希望它放弃。
例如。
final long start = System.currentTimeMillis();
myDataStructure.stream()
.while(() -> System.currentTimeMillis() <= start + 30000)
.forEach(e ->
{
...
});
如果满足某个条件,我希望避免在forEach
调用中只说return
。
发布于 2017-08-01 16:20:53
如果在这种情况下,与实际执行操作相比,迭代流或数组的成本更低,而不是只使用谓词并过滤时间是否已过。
final long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(30L);
myDataStructure.stream()
.filter(e -> System.nanoTime() <= end)
.forEach(e ->
{
...
});
问题是,您是否需要知道哪些元素已被处理。使用上述方法,您必须检查特定元素是否在事后发生了副作用。
发布于 2017-08-01 17:11:35
我将为此创建一个自定义池,如下所示:
ForkJoinPool forkJoinPool = new ForkJoinPool(1);
try {
forkJoinPool.submit(() ->
IntStream.range(1, 1_000_000).filter(x -> x > 2).boxed().collect(Collectors.toList()))
.get(30, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
// job not done in your interval
}
发布于 2017-08-01 16:24:58
您可以利用.allMatch()
是一个短路操作符的事实来终止流:
final long start = System.currentTimeMillis();
myDataStructure.stream()
.allMatch(e ->
{
// your task here
return System.currentTimeMillis() <= start + 30000;
});
https://stackoverflow.com/questions/45432373
复制相似问题