<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Object Mentor Blog: Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block</title>
    <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Always &amp;lt;tt&amp;gt;close()&amp;lt;/tt&amp;gt; in a &amp;lt;tt&amp;gt;finally&amp;lt;/tt&amp;gt; block</title>
      <description>&lt;p&gt;Here&amp;#8217;s one for my fellow Java programmers, but it&amp;#8217;s really generally applicable.&lt;/p&gt;


	&lt;p&gt;When you call &lt;tt&gt;close()&lt;/tt&gt; on I/O streams, readers, writers, network sockets, database connections, &lt;em&gt;etc.&lt;/em&gt;, it&amp;#8217;s easy to forgot the most appropriate idiom. I just spent a few hours fixing some examples of misuse in otherwise very good Java code.&lt;/p&gt;


	&lt;p&gt;What&amp;#8217;s wrong the following code?&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(fileName);
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
    writer.write(content);
    writer.close();
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;It doesn&amp;#8217;t look all that bad. It tells it&amp;#8217;s story. It&amp;#8217;s easy to understand.&lt;/p&gt;


	&lt;p&gt;However, &lt;em&gt;it&amp;#8217;s quite likely&lt;/em&gt; that you won&amp;#8217;t get to the last line, which closes the &lt;tt&gt;writer&lt;/tt&gt;, from time to time. File and network I/O errors are common. For example, what if you can&amp;#8217;t actually write to the location specified by &lt;tt&gt;fileName&lt;/tt&gt;? So, we have to be more defensive. We want to be sure we always clean up.&lt;/p&gt;


	&lt;p&gt;The correct idiom is to use a &lt;tt&gt;try &amp;#8230; finally &amp;#8230;&lt;/tt&gt; block.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(getFileSystemPath() + contentFilename);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
        writer.write(content);
    } finally {
        if (writer != null)
            writer.close();
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, no matter what happens, the writer will be closed, if it&amp;#8217;s not null, even if writing the output was unsuccessful.&lt;/p&gt;


	&lt;p&gt;Note that we don&amp;#8217;t necessarily need a &lt;tt&gt;catch&lt;/tt&gt; block, because in this case we&amp;#8217;re willing to let any &lt;tt&gt;Exception&lt;/tt&gt;s propagate up the stack (notice the throws clause). A lot of developers don&amp;#8217;t realize that there are times when you need a &lt;tt&gt;try&lt;/tt&gt; block, but not necessarily a &lt;tt&gt;catch&lt;/tt&gt; block. This is one of those times.&lt;/p&gt;


	&lt;p&gt;So, anytime you need to clean up or otherwise release resources, use a &lt;tt&gt;finally&lt;/tt&gt; block to ensure that the clean up happens, no matter what.&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 00:12:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:2eda3563-e87a-4c15-a93d-f842f8de8f68</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>close</category>
      <category>finally</category>
      <category>Java</category>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Steve Freeman</title>
      <description>&lt;p&gt;Jaap is right. The pattern should be&lt;/p&gt;


&lt;pre&gt;
Resource resource = makeResourceOrFail();
try {
  doSomethingWith(resource);
} finally {
  resource.close();
}&lt;/pre&gt;

	&lt;p&gt;The only way to be really sure of all the corner cases is to insist on keeping things this clean. It&amp;#8217;s not hard.&lt;/p&gt;</description>
      <pubDate>Tue, 05 Aug 2008 11:56:51 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:bf16c2d3-cc41-4e0c-9f35-2d4780cc9f40</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1933</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Dean Wampler</title>
      <description>&lt;p&gt;I guess I blew the example a bit with the nested writer/stream creation. It shows how tricky this can be to implement robustly. Good comments, all.&lt;/p&gt;


	&lt;p&gt;JuanM is right; a much better design would be for libraries with non-trivial recovery requirements to guarantee proper clean up, with a user specified closure or worker object to do the work on the open resources. Database Connections are another example where this design would be useful.&lt;/p&gt;


	&lt;p&gt;When I&amp;#8217;m designing an API, I try to ensure that there is no way the user can to use it incorrectly!&lt;/p&gt;</description>
      <pubDate>Sat, 02 Aug 2008 16:51:44 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:fd9cf500-87d6-4e63-af82-57e7165c7128</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1926</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Jaap Beetstra</title>
      <description>&lt;blockquote&gt;Jaap, how does your example code avoid the stream not being closed if OutputStreamWriter throws an exception?&lt;/blockquote&gt;

	&lt;p&gt;It doesn&amp;#8217;t, it&amp;#8217;s just somewhat more compact than the example in the posting.&lt;/p&gt;


In the example given it is not really an issue anyway, since the constructor cannot fail (famous last words). If this a concern, such as with a different encoding, you could do it like this:
&lt;pre&gt;
OutputStreamWriter writer = null;
OutputStream os= new FileOutputStream(output);
try {
  // UTF-7 might not be available
  writer = new OutputStreamWriter(os, "UTF-7");
  writer.write(content);
} finally {
  if (writer == null)
    os.close();
  else
    writer.close();
}
&lt;/pre&gt;</description>
      <pubDate>Fri, 01 Aug 2008 19:12:29 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:ce61ce8f-e624-447d-867e-41fb92ac816e</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1924</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by JuanM</title>
      <description>&lt;p&gt;This is one of the reasons why Closures would be useful for us Java Programmers, we could delegate the responsibility of closing the stream to the Stream, instead of closing it ourselves.&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 18:59:29 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:bc7e42bf-bd04-4fa5-ab05-201c12fe2d51</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1922</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Reader</title>
      <description>&lt;p&gt;You&amp;#8217;ve still got a potentially unclosed stream if OutputStreamWriter throws.  I think the following would cover that:
    FileOutputStream stream = null;
    try {
        stream = new FileOutputStream(output);
        writer = new OutputStreamWriter(stream, &amp;#8220;UTF-8&amp;#8221;);
        writer.write(content);
    } finally {
        if (writer != null)
            writer.close();
        else if(stream != null)
            stream.close();
    }&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 18:11:29 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:15d308c1-baaf-43e9-87c1-ffeefe702f0f</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1921</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Reader</title>
      <description>&lt;p&gt;Jaap, how does your example code avoid the stream not being closed if OutputStreamWriter throws an exception?  If it throws an exception the try block will never get executed and therefore the finally block will never get executed&amp;#8212;you&amp;#8217;re in the same situation as the original code.&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 18:05:48 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:34978af5-3d77-46be-a48a-f02fb2a2f308</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1920</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Andrew Rea</title>
      <description>&lt;p&gt;In C# we also have a using statment block:&lt;/p&gt;


	&lt;p&gt;using(FileStream fs1 = File.Open(@&amp;#8221;C:\MyTricks.txt&amp;#8221;))
{
//...Bla Bla Bla
}&lt;/p&gt;


	&lt;p&gt;This automatically deals with the try, finally block in MSIL code.  Nice shortcut and code/time saver in my opinion.&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 08:51:56 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:8d666aa4-4ec7-4187-a802-b40996d7a682</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1919</link>
    </item>
    <item>
      <title>"Always &lt;tt&gt;close()&lt;/tt&gt; in a &lt;tt&gt;finally&lt;/tt&gt; block" by Jaap Beetstra</title>
      <description>&lt;p&gt;You should be careful with the constructor chaining here. If for some reason the OutputStreamWriter constructor throws an exception, the stream will nog be closed, since &lt;code&gt;writer&lt;/code&gt; is not assigned yet. In this example it should not happen, but it would be possible if a different encoding is specified which is not necessarily available on the platform (iirc &lt;code&gt;UTF-8&lt;/code&gt; must be available according to the JLS).&lt;/p&gt;


I usuallly use the idiom below, which has the same caveat, but is slightly more compact. 
&lt;pre&gt;    
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
    try {
        writer.write(content);
    } finally {
        writer.close();
    }
&lt;/pre&gt;</description>
      <pubDate>Thu, 31 Jul 2008 00:37:56 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:2ad2488c-8a6a-4202-969d-f7582b4c3bf7</guid>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block#comment-1918</link>
    </item>
  </channel>
</rss>
