抛出异常并从最终返回 - Tomcat挂起

时间:2013-08-19 20:15:40

标签: java mysql performance tomcat exception-handling


最近我看到了tomcat服务器的频繁挂起,并且在代码的某些部分经常抛出一些异常。

当我检查代码时,这就是它的样子

public static String doSomething() {
    String returnVakue = "default value";

    try {
        ResultSet rs = getMyResultSet(); 

        rs.first(); 
        returnValue = rs.getString("my_field"); // Note that Exception happens at times when the ResultSet is empty

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        return returnValue;
    }

}

虽然我知道将两者抛出异常并返回是完全可以的,但是想知道这是否会导致tomcat中出现任何类型的泄漏。性能是否存在潜在风险? ?但是我的调用函数此时会停止执行。对此有何看法?它会影响GC吗?

编辑:注意: 我知道如何更正此代码。请分享您的观点是否可能导致tomcat挂起。

2 个答案:

答案 0 :(得分:0)

首先检查返回的ResultSet是否为空。

while( rs.next() ) {
    // ResultSet processing here
    // Result set is not empty
}

在我看来,抛出异常是你的决定,但最后你应该做清理,例如关闭连接。

如果未关闭,打开连接将导致tomcat挂起,因为来到服务器的新请求将等待连接变为可用。

引用的Java中的任何对象都不是garabage,在你的情况下,如果Connections没有关闭,那么这些对象将不会被垃圾收集。

干杯!!

答案 1 :(得分:0)

如果查询需要很长时间,而不是JDBC问题。数据库负责。当然,如果正确使用JDBC。另一方面,如果使用简单的JDBC,最好在应用程序中添加层DAO。

public class UserDAO extends DAO {

    private static final String FIND_BY_PK_SQL = 
        "SELECT mail, password " +
        "  FROM user WHERE mail = ?";

    public User findByPk(final String mail) throws DAOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(FIND_BY_PK_SQL);
            ps.setString(1, mail);
            rs = ps.executeQuery();
            if (rs.next()) {
                return fill(rs);
            }
            return null;
        } catch (final SQLException e) {
            throw new DAOException(e);
        } finally {
            DbUtils.closeQuietly(conn, ps, rs);
        }
    }

    private User fill(final ResultSet rs) throws SQLException {
        final User user = new User();
        user.setMail(rs.getString("mail"));
        user.setPassword(rs.getString("password"));
        return user;
    }
}