認識 Java Exception 和 Connection Poll

Posted in :

我寫了一支java程式,遇到一個神奇的狀況會把系統打趴,以為是系統環境的設定問題,最後找到是我對 try 的了解不夠造成。

有問題的 code:

if (conn != null) {
    try {
        CachedRowSet crs = null;
        crs = new CachedRowSetImpl();
        statement = conn.createStatement();
        statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS);
        crs.populate(statement.getGeneratedKeys());
        if (crs != null) {
            if (crs.next()) {
                ret = crs.getLong(1);
            }
            crs.close();
        }
        conn.close();
    } catch (SQLException e) {
        if (printSqlExcpetion) {
            Log.d(expression);
            Log.d("SQLException:" + e.toString());
        }
    }
}

正確的 code:

if (conn != null) {
    try {
        CachedRowSet crs = null;
        crs = new CachedRowSetImpl();
        statement = conn.createStatement();
        statement.executeUpdate(expression, Statement.RETURN_GENERATED_KEYS);
        crs.populate(statement.getGeneratedKeys());
        if (crs != null) {
            if (crs.next()) {
                ret = crs.getLong(1);
            }
            crs.close();
        }
    } catch (SQLException e) {
        if (printSqlExcpetion) {
            TKLog.d(expression);
            TKLog.d("SQLException:" + e.toString());
        }
    }
    try {
        conn.close();
    } catch (SQLException e) {
        TKLog.d("Force close connection:" + e.toString());
    }
}

如果是使用單純的 connection 不會有這個問題,遇到共用 connection 時,有程式沒有正確地關閉 connection 會造成其他人無法正確使用 connection pool 裡的 connection.

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *