Infinite parallel stream (original) (raw)

Boaz Nahum boaznahum at gmail.com
Tue Apr 30 01:50:59 PDT 2013


I'm trying to generate parallel stream from an infinite iterator:

    Stream<Data> s = generateParallel(supplier).
            parallel().
            limit(1000);

    s.forEach(System.out::println);

My Spliterator:

private static class ParallelGenerateSpliterator<T> implements

Spliterator {

    private final Supplier<? extends T> supplier;
    private long estimatedSize;

    public ParallelGenerateSpliterator(Supplier<? extends T> supplier,

long estimatedSize) { this.supplier = supplier; this.estimatedSize = estimatedSize; }

    public ParallelGenerateSpliterator(Supplier<? extends T> supplier) {
        this(supplier, 1 << Runtime.getRuntime().availableProcessors());
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        action.accept(supplier.get());
        return true;
    }

    @Override
    public Spliterator<T> trySplit() {

        long spliSize = estimatedSize >> 1;

        if (spliSize == 0) {
            return null;
        }

        estimatedSize -= spliSize;

        return new ParallelGenerateSpliterator<T>(supplier, spliSize);
    }

    @Override
    public long estimateSize() {
        return estimatedSize;
    }

    @Override
    public int characteristics() {
        return IMMUTABLE;
    }
}

But the examples above run for ever, loop endlessly in AbstractPipeline:

        spliterator.forEachRemaining(wrappedSink);

Can I solve it without making spliterator non infinite ?

Thank Boaz



More information about the lambda-dev mailing list