Why is BufferedReader not closed when obtaining `Stream<String>` in try-with-resources?
autocloseable, java, java-8, java-stream, try-with-resources
Solution
I haven't actually used try-resources syntax. Wish my answer makes sense.
From my understanding, auto-close is closing the resource declared at the statement, nothing else.
Therefore, `try(Stream<String> lines = new BufferedReader(r).lines()) {` is simply closing `lines`, but not that buffered reader that have no variable assigned.
If you are intended to close both the buffered reader and the stream (do you really need to close the stream anyway?), iirc, you can have multiple lines in the try statement:
try (BufferedReader br = new BufferedReader(r);
Stream<String> lines = br.lines()) {
//....
}
somethings like that. (Haven't tried to compile that, wish it works :P)
Problem
The reader should be closed when a `Stream` is used in a try-with-resources. Given this: ``` try(Stream<String> lines = new BufferedReader(reader).lines()) { return lines.map(it -> trim ? it.trim() : it) .collect(Collectors.toList()); } ``` ... the reader is not being closed?? This test fails: ``` AtomicBoolean closed = new AtomicBoolean(false); Reader r = new StringReader(" Line1 \n Line2") { @Override public void close() { super.close(); closed.set(true); } }; try(Stream<String> lines = new BufferedReader(r).lines()) { lines.map(it -> trim ? it.trim() : it) .collect(Collectors.toList()); } assertTrue("Reader was not closed.",closed.get()); ```