Limiting infinite parallel stream
<p>1) How can I use a Supplier (<code>supplier</code>) to create a sized stream of N values in parallel, while ensuring that no more than N calls are made to the supplier? I need this because I have a supplier with a costly <code>supplier.get()</code> operation.</p>

<p>2) The 'obvious' answer to my question, <code>Streams.generate(supplier).limit(N)</code>, does not work and often results in more than N calls being made to the supplier. Why is this?</p>

<p>As 'proof' of the fact that <code>Streams.generate(supplier).limit(N)</code> results in more than N calls to <code>supplier.get()</code>, consider the following code:</p>

<pre class="lang-java prettyprint-override"><code>public class MWE {
    static final int N_ELEMENTS=100000;
    static Supplier&lt;IntSupplier&gt; mySupplier = () -&gt; new IntSupplier() {
        AtomicInteger ai = new AtomicInteger(-1);
        @Override
        public int getAsInt() {
            return ai.incrementAndGet();
        }
    };
    public static void main(String[] args) {
        int[] a = IntStream.generate(mySupplier.get()).limit(N_ELEMENTS).toArray();
        int[] b = IntStream.generate(mySupplier.get()).parallel().limit(N_ELEMENTS).toArray();
    }
}
</code></pre>

<p><code>a</code> is equal to <code>[0, 1, ..., N_ELEMENTS-1]</code> as expected, but contrary to what you might expect <code>b</code> does not contain the same elements as <code>a</code>. Instead, <code>b</code> often contains elements that are greater than or equal to <code>N_ELEMENTS</code>, which indicates more than <code>N_ELEMENTS</code> number of calls to the supplier.</p>

<p>Another illustration would be that <code>Streams.generate(new Random(0)::nextDouble()).limit(5)</code> does not always generate the same set of numbers.</p>