class StreamContext {
    static final StreamContext SEQUENTIAL = new StreamContext(false);
    static final StreamContext PARALLEL = new StreamContext(true);

    boolean parallel;
    ForkJoinPool fjp;
    Runnable closeHandler;

    private StreamContext(boolean parallel) {
        this.parallel = parallel;
    }

    <T> T terminate(Supplier<T> terminalOperation) {
        return fjp.submit(terminalOperation::get).join();
    }

    <T, U> T terminate(U value, Function<U, T> terminalOperation) {
        return fjp.submit(() -> terminalOperation.apply(value)).join();
    }

    StreamContext parallel() {
        if (this == SEQUENTIAL)
            return PARALLEL;
        this.parallel = true;
        this.fjp = null;
        return this;
    }

    StreamContext sequential() {<FILL_FUNCTION_BODY>}

    StreamContext parallel(ForkJoinPool fjp) {
        StreamContext context = detach();
        context.parallel = true;
        context.fjp = fjp;
        return context;
    }

    StreamContext detach() {
        if (this == PARALLEL || this == SEQUENTIAL)
            return new StreamContext(parallel);
        return this;
    }

    StreamContext onClose(Runnable r) {
        StreamContext context = detach();
        context.closeHandler = compose(context.closeHandler, r);
        return context;
    }

    void close() {
        if (closeHandler != null) {
            Runnable r = closeHandler;
            closeHandler = null;
            r.run();
        }
    }

    static Runnable compose(Runnable r1, Runnable r2) {
        if (r1 == null)
            return r2;
        return () -> {
            try {
                r1.run();
            } catch (Throwable t1) {
                try {
                    r2.run();
                } catch (Throwable t2) {
                    t1.addSuppressed(t2);
                }
                throw t1;
            }
            r2.run();
        };
    }

    StreamContext combine(BaseStream<?, ?> other) {
        if (other == null)
            return this;
        StreamContext otherStrategy = of(other);
        StreamContext result = this;
        if (other.isParallel() && !parallel)
            result = parallel();
        if (otherStrategy.closeHandler != null)
            result = result.onClose(otherStrategy.closeHandler);
        return result;
    }

    static StreamContext of(BaseStream<?, ?> stream) {
        if (stream instanceof BaseStreamEx)
            return ((BaseStreamEx<?, ?, ?, ?>) stream).context;
        return new StreamContext(stream.isParallel()).onClose(stream::close);
    }
}

        if (this == PARALLEL)
            return SEQUENTIAL;
        this.parallel = false;
        this.fjp = null;
        return this;
    
<no_super_class>