1

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.

MusikPolice
  • 1,699
  • 4
  • 19
  • 38
  • 1
    I think you will be returning a closed stream with this code. Generally when you allocate an important resource you want to close it in the same scope as it was acquired which is exactly what try-with-resources encourages. If you have to do it in this fashion I would return a supplier of the InputStream and then call that in the try-with-resources block. – SephB Oct 13 '20 at 20:54
  • Sorry for misunderstanding to start with -- but the "better thing to do" is to have your callers use try-with-resources themselves. – Louis Wasserman Oct 13 '20 at 21:09
  • Your spidey sense has the right idea -- it'll be returning a closed stream, which is almost useless... I suppose exceptions when you try to read from it could communicate its closed-ness. So, there's no resource leak, but also not many ways to use the returned stream. Now, we often use streams to enable handling large data sets, and copying the contents of the stream to some other object usually means loading the entire contents into memory -- beware. An alternative is to return the stream here, but have an unskippable shutdown/close method that remembers opened resources and closes them. – Gus Oct 13 '20 at 21:12

1 Answers1

2

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

Elmar Brauch
  • 1,286
  • 6
  • 20