Tomcat连接池放弃了问题

时间:2017-11-22 13:17:57

标签: java tomcat jdbc tomcat7

我正在努力解决Tomcat连接池错误。运行生成String值的简单存储过程后,会在运行时抛出以下错误。

WARNING: Connection has been abandoned PooledConnection[ConnectionID:45 ClientConnectionId: 7817280c-3f7e-4239-a009-3aedd0a855e8]:java.lang.Exception
    at org.apache.tomcat.jdbc.pool.ConnectionPool.getThreadDump(ConnectionPool.java:1096)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:799)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:648)
    at org.apache.tomcat.jdbc.pool.ConnectionPool.getConnection(ConnectionPool.java:200)
    at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:128)
    at util.ThreadLocalUtil.getConnection(ThreadLocalUtil.java:55)
    at webapp.dao.WebApplicationDAO.getConnection(WebApplicationDAO.java:30)
    at webapp.dao.AccountDAO.generateAccountId(AccountDAO.java:827)
    at webapp.bo.Account.generateUserAccountId(Account.java:285)
    at webapp.actions.AddUserAccountUNZAction.execute(AddUserAccountUNZAction.java:79)
    at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
    at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
    at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)

我对该错误的了解是连接已打开但未关闭。在帐户dao中运行存储过程时打开连接。下面是调用存储过程的代码块。

Connection conn = null;
    CallableStatement stmt = null;
    ResultSet rs = null;
    try {

        conn = getConnection();
        stmt = conn.prepareCall(sqlWebAppGenerateUserId);
        stmt.setString(1, base);
        rs = stmt.executeQuery();
        String res = null;
        if (rs.next()) {
            res = rs.getString(1);
        }

        if (res == null) {
            throw new RuntimeException("Failed to generate user id.");
        }

        return res;
    } catch (SQLException e) {
        LOG.error("{}", e);
        throw new RuntimeException(e);
    }finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error(e.getMessage(), e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
                conn.close();
            } catch (SQLException e) {
                LOG.error(e.getMessage(), e);
            }
        }

    }

如您所见,我使用finally块来关闭连接等。

我无法解释错误被抛出的原因,以及我如何调试和解决此问题。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

仅在conn时关闭rs != null,这意味着每次查询失败时,连接都不会关闭。

我还建议切换到try-with-resources,而不是编写笨拙的finally块,这可能会导致错误。

答案 1 :(得分:0)

@Kayaman说的是什么。此外,如果语句执行时间超过removeAbandonedTimeout,则可能会发生这种情况。