Closing the Stream returned from BufferedReader.lines()
Zhong Yu
zhong.j.yu at gmail.com
Mon Dec 2 10:45:38 PST 2013
On Mon, Dec 2, 2013 at 3:20 AM, Alan Bateman <Alan.Bateman at oracle.com> wrote:
> On 02/12/2013 03:03, Zhong Yu wrote:
>>
>> In this code
>>
>> BufferedReader br = ...;
>> Stream<String> stream = br.lines();
>> stream.close(); // does not close `br`
>>
>> `stream.close()` does not trigger `br.close()`. I for one find that
>> rather counter-intuitive. Can you guys explain the design choice? When
>> should a Stream forward close() to its source and when should it not?
>>
> See discussion on core-libs-dev from about a week ago on the same topic:
>
> http://mail.openjdk.java.net/pipermail/core-libs-dev/2013-November/023289.html
That discussion centers around the argument that `Stream.close()`
should not be invoked anyway under the circumstance.
However, what if it *is* invoked? What is the reason then that the
stream does not close its data source when it is asked to close
itself?
The only reason I can think of is to punish the programmer for not
following the best practice of open-close pairing so that they'll be
whipped into having some good senses. That should only happen if the
best practice is carved in stone, which is not the case here. It is
perfectly legitimate, and occurring frequently in practice, that the
ownership of a data source is transferred around through some
predefined protocols, therefore the responsibility of `close` also
changes hand.
And we also want to write one liners like
try(Stream<String> lines = new BufferredReader(new MyWebReader())))
It's reasonable to expect that this should work, and `lines.close()`
should propagate all the way to `MyWebReader.close`.
And all the java.io wrapper classes forward `close` call to their
sources, I don't see why the same strategy should not apply to
`BufferredReader.lines()` which also creates a wrapper object.
Zhong Yu
More information about the lambda-dev
mailing list