Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing stream chains & try-with-resource

my first question on stackoverflow, I'm exited ;)

When using stream chains it's usually good pratice to just close the last stream in the chain, since the close() operation should propagate through all streams of the chain.

What would be considered good practice when combining try-with-ressource statements and stream chaining?

a) Creating all streams inside the try statement:

try (InputStream processIn = p.getInputStream();
            InputStreamReader inReader = new InputStreamReader(processIn);
            BufferedReader input = new BufferedReader(inReader)) { 
    .
    .
}

Or b) just the last member of the chain:

InputStream processIn = p.getInputStream();
InputStreamReader inReader = new InputStreamReader(processIn);
try (BufferedReader input = new BufferedReader(inReader)) { 
    .
    .
}

I guess both versions will work in the end, but I assume a) will generate duplicate close() calls, won't it?

like image 809
Johnson Avatar asked Jan 16 '14 15:01

Johnson


People also ask

Why should you always close streams?

If you don't close streams, you may have problems opening them back up again. This is especially true if they're hanging off the end of sockets. Closing a stream also makes sure that data is flushed through the stream if there is any data left to send.

Do we need to close Java streams?

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.

How do I close an output stream?

close() method closes this output stream and releases any system resources associated with this stream. The general contract of close is that it closes the output stream. A closed stream cannot perform output operations and cannot be reopened.

What is the right way to close the streams in Java?

The java. io. InputStream. close() method closes this stream and releases any system resources associated with the stream.


1 Answers

Good practice is option a).

If you are using option b) then if initialization of stream inReader fails then stream processIn will not get closed.

On the other hand if you are using option a) then every stream will be closed correctly. Of course, if you are chaining streams then the first stream in chain may be attempted to get closed multiple times, but this is ok for streams because they all implement Closeable, which requires method close() to be idempotent (i.e. if the stream has been already closed then additional invocations of close() should have no effect).

You can find additional information here and here.

like image 108
Andrii Polunin Avatar answered Oct 14 '22 05:10

Andrii Polunin