5

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?

1 Answer 1

6

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.

1
  • I didn't consider the possible initialization problem. Everyone reading this should also read your second link describing a similar problem. Both cases are rather obvious when you think about it, but can easily be overlooked. Thanks for the hints!
    – Johnson
    Feb 6, 2014 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.