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?
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.
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.
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.
The java. io. InputStream. close() method closes this stream and releases any system resources associated with the stream.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With