<?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>Late to the Party: Close your Streams</title>
    <link>http://cwilliams.textdriven.com/articles/2005/07/15/close-your-streams</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Ruby. Rails. Stuff.</description>
    <item>
      <title>Close your Streams</title>
      <description>&lt;p&gt;All right, so this post isn't for most programmers out there. It is, however, meant for any new Java programmers, or just really aloof ones.&lt;/p&gt;
&lt;p&gt;I work at a large Fortune 500 company as a contractor. We're working on a project in Java that is now on about it's 4th or 5th year of life.&lt;/p&gt;
&lt;p&gt;One of my co-workers, who's been working on the project for at least 3 years now had the following code in one of her classes:&lt;/p&gt;
&lt;pre class="code"&gt;
try {
  Connection conn = getConnection(url);
  Request req = new Request(message);
  Response resp = conn.sendMessage(req);
  if (resp == null || resp.isErrorCode()) {
    sendFailure();
  } else {
    sendSuccess();
  }
  conn.close();		           			
} catch (IOException e) {
  e.printStackTrace();		           		
}	
&lt;/pre&gt;
&lt;p&gt;See the problem?&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Exactly.&lt;/strong&gt; She didn't close her socket in a finally clause. That means if we do get an Exception, the socket might never be closed properly.&lt;/p&gt;
&lt;p&gt;She should have done something like this:&lt;/p&gt;
&lt;pre class="code"&gt;
Connection conn = null;
try {
  conn = getConnection(url);
  Request req = new Request(message);
  Response resp = conn.sendMessage(req);
  if (resp == null || resp.isErrorCode()) {
    sendFailure();
  } else {
    sendSuccess();
  }           			
} catch (IOException e) {
  e.printStackTrace();		           		
} finally {
  try {
    // always properly close the connection
    if(conn != null) conn.close();
  } catch (CommException e) {
    // ignore
  }
}			
&lt;/pre&gt;
&lt;p&gt;Just another reason why Ruby is nicer. Using the block form of IO.open ensures that the stream will always get closed, and that we don't have to do all sorts of double-wrapping with try-catch code.&lt;/p&gt;</description>
      <pubDate>Fri, 15 Jul 2005 15:57:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:5a23a0793b7012f967d727afb6173c43</guid>
      <author>cwilliams</author>
      <link>http://cwilliams.textdriven.com/articles/2005/07/15/close-your-streams</link>
      <category>Programming</category>
      <category>Ruby</category>
      <category>Java</category>
    </item>
  </channel>
</rss>
