Should forEach() automatically close the stream?
alahijani at gmail.com
Thu Jun 27 04:42:07 PDT 2013
The current design of close has the undesirable property that an stream has
two independent notion of consumption. Consider this:
Stream<String> st = Files.lines(new File(path));
The stream cannot be used in any meaningful way after forEach, because
forEach is a terminal operation. So why give the user the option _not_ to
Disregarding the current round on close(), stream has a well defined notion
of consumption defined as being drained by a terminal operation. Even more:
the lazy intermediate operations which do not consume the underlying data
source, do invalidate the receiver stream, so that there is never more than one
stream instance in charge of an underlying data source.
This is a spectacularly well-defined resource management invariant. So why
not use this invariant to manage GCR resources as well? When the only
instance operating on a GCR resources is consumed by a terminal operation,
it would be very natural to expect it to also take care of releasing
underlying GCR resources at the end.
So it appears that stream does not need a close() method at all. You could
do stream.forEach(NOP) and it would automatically release all underlying
resources. But since this would be usually wasteful, we need a close()
method *only as a short-circuiting device*. We need this short-circuiting
only because forEach(NOP) would be wasteful for most streams, and
impossible for infinite ones.
More information about the lambda-libs-spec-observers