mercoledì 12 febbraio 2014

Try-with-resources

In several Java APIs, closing resources have to be managed manually, usually by a call to a close method in a finally block. This is the case for resources managed by the operating system such as files, sockets, or JDBC connections.
The following example shows how it is necessary to put the closing code in a finally block with exception handling, which decreases the readability of the code:
@Resource(lookup = "java:/MySQLDS")
private DataSource ds;
. . . .  
String sql = "select * from customer";
List list = new ArrayList();
Connection con =null;
PreparedStatement ps =null;
ResultSet rs =null;
try {
   con = ds.getConnection();
   ps = con.prepareStatement(sql);
 
   rs = ps.executeQuery();
        while (rs.next()) {
            list.add(rs.getInt("id"));
   }
   
} catch (SQLException e) {
    e.printStackTrace();
}
 finally {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {  }
    }
    if (ps != null) {
        try {
            ps.close();
        } catch (SQLException e) {  }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {  }
    }
}
And here's the same example rewritten to use try-with-resource:
@Resource(lookup = "java:/MySQLDS")
private DataSource ds;
. . . .  
String sql = "select * from customer";
List list = new ArrayList();
try (Connection con = ds.getConnection();
     PreparedStatement ps = con.prepareStatement(sql);) {
 
    try (ResultSet rs = ps.executeQuery();) {
        while (rs.next()) {
            list.add(rs.getInt("id"));
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

Nessun commento:

Posta un commento