Who closes an `InputStream` that is Returned from within a try with resources block?

864 Views Asked by At

When doing a code review, I stumbled on some code that looks like this:

try (InputStream stream = new BufferedInputStream(resource)) {
    return stream;
}

where resource was defined elsewhere in the method. Note that this is sample code and that in real life, it's important that stream is closed so as not to leak resources.

My question is this: Will the try with resources block close stream on my behalf? Once stream has been returned to the caller, they might try to do something useful with it, or god forbid, hold a reference to it in a global variable that never gets cleaned up.

Will the try with resources block follow this reference around and dutifully clean it up? I can't find an answer to this in any of the tutorials or docs that I've read about this syntax.

My spidey sense is tingling and telling me that the better thing to do would be to copy the contents of the stream to some other object and then return that object to ensure that the stream is closed.

1

There are 1 best solutions below

0
On BEST ANSWER

The Stream will be closed, if it is returned inside the try-with block.

This question was already asked, see here:
If it safe to return an InputStream from try-with-resource