防止java.lang.StackOverflow错误简单的sql池

时间:2018-06-04 11:54:19

标签: java

所以我正在运行多个sql调用,并且我有一个自定义的'sql pool'连接,但是它开始发送java.lang.stackoverflow错误。我该如何防止这种情况发生。这是我目前的代码。

public static synchronized PooledSqlConnection getConnectionFromPool() {
    for(PooledSqlConnection connection : pooledSqlConnections) {
        if(connection.getConnection() == null) {
            connection.setUpConnection();
        }
        if(!connection.isInUse()) {
            connection.setInUse(true);
            return connection;
        }
    }
    return getConnectionFromPool();
}

这样的事情会有效吗?

public static synchronized PooledSqlConnection getConnectionFromPool() {
    boolean foundPool = false;
    while(!foundPool) {
        for(PooledSqlConnection connection : pooledSqlConnections) {
            if(connection.getConnection() == null) {
                connection.setUpConnection();
            }
            if(!connection.isInUse()) {
                connection.setInUse(true);
                foundPool = true;
                return connection;
            }
        }
    }
    return null;
}

每次使用连接时,都会将其标记为正在使用,一旦完成,就会将其标记为未使用。

2 个答案:

答案 0 :(得分:1)

当您未能找到可用连接时,您决定进行递归调用似乎不是一个好主意。当可用连接用完时,它会导致无限递归和StackOverflowError

除了递归调用之外,您可以使用另一个for循环来包装for循环,该循环将在内循环的每次迭代后休眠(以释放被占用的连接时间)。 / p>

或者,如果没有可用的连接,则抛出异常。这将使getConnectionFromPool()的调用者负责在抛出异常时重试。

答案 1 :(得分:0)

堆栈溢出似乎很可能是由对getConnectionFromPool()的递归调用引起的。要避免它,您需要解除对方法的解除,如下所示:

public static synchronized PooledSqlConnection getConnectionFromPool() {
    while (true) {
        for(PooledSqlConnection connection : pooledSqlConnections) {
            if(connection.getConnection() == null) {
                connection.setUpConnection();
            }
            if(!connection.isInUse()) {
                connection.setInUse(true);
                return connection;
            }
        }
        // If we reach this stage, there is no available connection.
        // FIXME: Add some form of sleep and/or wait
        // to be notified once a connection is available.
    }
}

注意我对PooledSqlConnection的了解不足以确保此代码段完全有效。