Do I need to close a ByteArrayInputStream?

JavaGarbage CollectionInputstream

Java Problem Overview


Short question,

I saw in some old code where a ByteArrayInputStream was created like:

new BufferedReader(new InputStreamReader(new ByteArrayInputStream(somebytes)));

And then the BufferedReader is used to read out somebytes line by line.
All working fine, but I noticed that the BufferedReader is never closed.
This is all working in a long running websphere application, the somebytes are not terrible big (200k most), it is only invoked a few times a week and we're not experiencing any apparent memory leaks. So I expect that all the objects are successfully garbage collected.

I always (once) learned that input/output streams need to be closed, in a finally statement. Are ByteStreams the exception to this rule?

kind regards Jeroen.

Java Solutions


Solution 1 - Java

You don't have to close ByteArrayInputStream, the moment it is not referenced by any variable, garbage collector will release the stream and somebytes (of course assuming they aren't referenced somewhere else).

However it is always a good practice to close every stream, in fact, maybe the implementation creating the stream will change in the future and instead of raw bytes you'll be reading file? Also static code analyzing tools like PMD or FindBugs (see comments) will most likely complain.

If you are bored with closing the stream and being forced to handle impossible IOException, you might use IOUtils:

IOUtils.closeQuietly(stream);

Solution 2 - Java

It is always good practice to close your readers. However not closing a ByteArrayInputStream does not have as heavy of a potential negative effect because you are not accessing a file, just a byte array in memory.

Solution 3 - Java

As @TomaszNurkiewicz mentioned it's always good to close the opened stream. Another good way to let it do the try block itself. Use try with resource like.......

try ( InputStream inputStream = new ByteArrayInputStream(bytes); Workbook workBook = new XSSFWorkbook(inputStream)) { 

 

here Workbook and InputStream both implements Closeable Interface so once try block completes ( normally or abruptly), stream will be closed for sure.

Solution 4 - Java

Resources need to be closed in a finally (or equivalent). But where you just have some bytes, no it doesn't matter. Although when writing, be careful to flush in the happy case.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondr jerryView Question on Stackoverflow
Solution 1 - JavaTomasz NurkiewiczView Answer on Stackoverflow
Solution 2 - JavajzdView Answer on Stackoverflow
Solution 3 - JavaKulDeepView Answer on Stackoverflow
Solution 4 - JavaTom Hawtin - tacklineView Answer on Stackoverflow