29

I have the following piece of code in a try/catch block

 InputStream inputstream = conn.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); 

My question is that when I have to close these streams in the finally block, do I have to close all the 3 streams or just closing the befferedreader will close all the other streams ?

1

6 Answers 6

31

By convention, wrapper streams (which wrap existing streams) close the underlying stream when they are closed, so only have to close bufferedreader in your example. Also, it is usually harmless to close an already closed stream, so closing all 3 streams won't hurt.

Sign up to request clarification or add additional context in comments.

4 Comments

You cannot guarantee that an stream implementation will not throw an exception when closing it if it is already close. So it is way better to stick to the proper way and close just the BufferedReader
@Soronthar Then this stream implementation is not valid by contract which states If the stream is already closed then invoking this method has no effect. All valid implementations MUST behave like this. It is totally legit (and common) to close an already closed stream. Typically you close it first time in try-block and a second time in the finally block where closing in try-block gives you the chance to react on exception and closing in finally block is for ensuring the close.
@FabianBarney you're right, I forgot they retrofitted the streams with the Closeable interface in JSE 6.
It's not just by convention, it is specified. See for example FilerInputStream.close().
8

Normally it is ok to just close the most outer stream, because by convention it must trigger close on the underlying streams.

So normally code looks like this:

BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); ... in.close(); // when you care about Exception-Handling in case when closing fails } finally { IOUtils.closeQuietly(in); // ensure closing; Apache Commons IO } 

Nevertheless there may be rare cases where an underlying stream constructor raises an exception where the stream is already opened. In that case the above code won't close the underlying stream because the outer constructor was never called and in is null. So the finally block does not close anything leaving the underlying stream opened.

Since Java 7 you can do this:

 try (OutputStream out1 = new ...; OutputStream out2 = new ...) { ... out1.close(); //if you want Exceptions-Handling; otherwise skip this out2.close(); //if you want Exceptions-Handling; otherwise skip this } // out1 and out2 are auto-closed when leaving this block 

In most cases you do not want Exception-Handling when raised while closing so skip these explicit close() calls.

Edit Here's some code for the non-believers where it is substantial to use this pattern. You may also like to read Apache Commons IOUtils javadoc about closeQuietly() method.

 OutputStream out1 = null; OutputStream out2 = null; try { out1 = new ...; out2 = new ...; ... out1.close(); // can be skipped if we do not care about exception-handling while closing out2.close(); // can be skipped if we ... } finally { /* * I've some custom methods in my projects overloading these * closeQuietly() methods with a 2nd param taking a logger instance, * because usually I do not want to react on Exceptions during close * but want to see it in the logs when it happened. */ IOUtils.closeQuietly(out1); IOUtils.closeQuietly(out2); } 

Using @Tom's "advice" will leave out1 opened when creation of out2 raises an exception. This advice is from someone talking about It's a continual source of errors for obvious reasons. Well, I may be blind, but it's not obvious to me. My pattern is idiot-safe in every use-case I can think of while Tom's pattern is error-prone.

13 Comments

Please don't do that sort of null dance. It's a continual source of errors for obvious reasons. And what a mess.
This is the normal pattern. What else you want to do?
acquire(); try { use(); } finally { release(); }
@Bruno Right - that's what I meant in the last paragraph.
@TomHawtin-tackline So you do not realease when acquire raises an Exception? This is bad, especially when using special OutputStreams like TeeOutputStream where creation of one already proceeded and the other one fails.
|
4

Closing the outermost one is sufficient (i.e. the BufferedReader). Reading the source code of BufferedReader we can see that it closes the inner Reader when its own close method is called:

513 public void close() throws IOException { 514 synchronized (lock) { 515 if (in == null) 516 return; 517 in.close(); 518 in = null; 519 cb = null; 520 } 521 } 522 } 

Comments

0

As a rule of thumb, you should close everything in the reverse order that you opened them.

Comments

0

I would close all of them in the inverse order from which you have opened them, as if when opening them would push the reader to a stack and closing would pop the reader from the stack.

In the end, after closing all, the "reader stack" must be empty.

2 Comments

What is your reason for this recommendation? When filtered input streams and readers are specified to close the nested stream on close()?
Just common sense, I guess. There are better answers in this thread, as the votes show. Some have even shown the source code for the library.
0

You only need to close the actual resource. You should close the resource even if constructing decorators fails. For output, you should flush the most decorator object in the happy case.

Some complications:

  • Sometimes the decorators are different resources (some compression implementations use the C heap).
  • Closing decorators in sad cases actually causes flushes, with ensuing confusion such as not actually closing the underlying resource.
  • It looks like you underlying resource is a URLConnection, which doesn't have a disconnect/close method as such.

You may wish to consider using the Execute Around idiom so you don't have to duplicate this sort of thing.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.