开发者

Strange OutOfMemoryError on Stream

开发者 https://www.devze.com 2023-01-14 11:16 出处:网络
Why do I get OutOfMemoryError for the f开发者_运维技巧ollowing code? Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).headStreams have some limitations on the JVM. The problem you are se

Why do I get OutOfMemoryError for the f开发者_运维技巧ollowing code?

Stream.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).head


Streams have some limitations on the JVM. The problem you are seeing here is that the Stream you are creating with Stream.from(1) is put on the stack and thus the JVM refuses to garbage collect it. The predicate you are passing to the filter call lets the Stream grow to 232792560 elements.

If you use an Iterator you can work around this limitation:

Iterator.from(1).filter(n => (1 to 20).forall(x => n % x == 0)).next


Streams are lazily evaluated, but they store the results of their evaluations. Thus, unless you want to traverse through them multiple times, you should use Iterator instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消