Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seq should auto-close underlying Stream #183

Open
lukaseder opened this issue Jan 12, 2016 · 0 comments
Open

Seq should auto-close underlying Stream #183

lukaseder opened this issue Jan 12, 2016 · 0 comments

Comments

@lukaseder
Copy link
Member

This can be implemented by wrapping the stream via the following pattern:

    class AutoClosingStream<R> implements Stream<R> {

        AutoClosingStream(Stream<R> delegate, Consumer<Optional<Throwable>> onClose) {}

        // Pipeline op
        @Override
        public Stream<R> limit(long maxSize) {
            return new AutoClosingStream(delegate.limit(maxSize));
        }

        // Terminal op
        @Override
        public void forEach(Consumer<? super R> action) {
            terminalOp(() -> delegate.forEach(action));
        }

        private void terminalOp(Runnable runnable) {
            terminalOp(() -> { runnable.run(); return null; });
        }

        private <R1> R1 terminalOp(Supplier<R1> supplier) {
            R1 result = null;

            try {
                result = supplier.get();
                onClose.accept(Optional.empty());
            }
            catch (Throwable e) {
                onClose.accept(Optional.of(e));
                Utils.sneakyThrow(e);
            }

            return result;
        }
    }

Such an AutoClosingStream would need to take care of implementing all future methods, e.g. from JDK 9, etc.

See also jOOQ/jOOQ#4932

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant