Sunday, January 8, 2012

Java 7 new features - 2. Automatic Resource Management


<< Previous Table of Categories Next >>


With this feature, resources such as Connections, Files, Input/OutStreams, etc. will be closed automatically in the "try" block rather than done manually by the developer. I personally think this is one of the most important features. Prior to Java 7, developers have to remember to close resource when programming in JDBC, Socket, File IO and etc. They need to do something like:
 
 try 
 {
  ...
 } 
 catch (SQLException e) 
 {
   // handle exception
 } 
 finally 
 {
  ...
  if (conn != null) 
  {
    try 
    {
      conn.close();
    } 
    catch (SQLException e)  
    {
    }
    conn = null;
  }
  ...
 }
This is not only annoying, but also error-prone. Especially for JDBC, if there are too many pending connections, the database will stop working in the end. In Java 7, you can use and test the automatic resource management like following:
 
 ...
 Connection conn = null;
 try(Connection connection=DriverManager.getConnection(url, "username", "password"))
 {
  conn=connection;
  ...
 }
 //the following code is just for testing
 try
 {
   System.out.println("connection isClosed? "+conn.isClosed());
 }
 catch(Exception e){}
Unfortunately however not all Java IDEs have a good support for this feature, some of them will complain "not a valid expression statement". So when you want to use this feature, please make sure that you have the latest IDE.

1 comment:

  1. JDK 7's Project coin is good enhancement in programmers armory for day 2 day work, though not big as changes in Java5. Out of all features
    automatic resource management and fork join framework in java7 is my favorite with bit of interest on multiple catch block for exceptions. What I don't find much useful is diamond operator, why do you have it in place, it would have been better if compiler infer it from either side.

    ReplyDelete