Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method may fail to close stream on exception

I get a critical error with findbugs:

The method creates an IO stream object, does not assign it to any fields, pass it to other methods, or return it, and does not appear to close it on all possible exception paths out of the method. This may result in a file descriptor leak. It is generally a good idea to use a finally block to ensure that streams are closed.

try {
...
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...
} catch (IOException e) {
    throw new RuntimeException(e);
} finally {
    try {
        if (stdError != null) {
            stdError.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

Do I need to close InputStreamReader also or p.getErrorStream (it returns InputStream)?

like image 257
IAdapter Avatar asked Apr 17 '10 10:04

IAdapter


People also ask

Do we have to close the stream always?

You should always close a stream in order to free open resources on your OS. Opening a stream always returns an identifier which you can use to close it wherever you are in your code (as long as the identifier is valid), whether their from another method or class.

Which method will close the stream pipeline?

collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.

Do we have to close the stream always Java?

Streams have a BaseStream. close() method and implement AutoCloseable , but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files. lines(Path, Charset) ) will require closing.

What happens if you don't close a stream in Java?

IO Resources. Under the hood, this method opens a FileChannel instance and then closes it upon stream closure. Therefore, if we forget to close the stream, the underlying channel will remain open and then we would end up with a resource leak.


2 Answers

What happens when an exception is thrown while creating the BufferedReader object? The stream managed by the InputStreamReader object is not closed until some time in the future when the garbage collector decides to destroy the object.

You will likely have similar problems if an exception is thrown while creating the InputStreamReader object.

like image 163
Matthew T. Staebler Avatar answered Sep 19 '22 20:09

Matthew T. Staebler


BufferedReader and InputStreamReader both close the underlying stream when they are closed. You should be fine by closing stdError

like image 34
Guillaume Avatar answered Sep 19 '22 20:09

Guillaume