Length of an infinite IntStream?

  • A+

I have created an randomIntStream by this:

 final static PrimitiveIterator.OfInt startValue = new Random().ints(0, 60).iterator(); 

The documentation says this stream is actually endless.

I want to understand what happens there in the backround.

ints(0,60) is generating an infinite stream of integers. If this is infinite, why my machine is not leaking any memory?

I wonder, how many numbers are actually really generated and if this implemenentation can cause an error at the point where the stream still ends? Or will this stream constantly filled with new integers on the fly and it really never ends therefore?

And if I already ask this question, what is the best practise right now to generate random numbers nowadays?


To be exact, IntStream java.util.Random.ints(int randomNumberOrigin, int randomNumberBound) returns

an effectively unlimited stream of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).

This doesn't mean infinite. Looking at the implementation (I'm looking at a JDK 8 implementation), it actually limits the created IntStream to Long.MAX_VALUE elements:

@implNoteThis method is implemented to be equivalent to ints(Long.MAX_VALUE, randomNumberOrigin, randomNumberBound).

Of course this is a very large number, and therefore it can be seen as "effectively" without limit. If you consume 1000000 ints every second, it will take you about 292471 years to run out of elements.

That said, as mentioned by the other answers, that IntStream only generates as many numbers as are required by its consumer (i.e. the terminal operation that consumes the ints).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: