}
public static java.sql.Connection getConnection(String poolName)
throws SQLException
{
CodeTimer timer = new CodeTimer();
CodeTimerSegment segment = timer.start("ConnectionPool: getConnection");
segment.setCanBeSubSegmentOnlyIfUnacceptable( true );
ConnectionPool pool = (ConnectionPool) poolsByDb.get(poolName);
if ( pool == null ) {
throw new IllegalStateException("The ConnectionPool (" + poolName + ") has not been initialized yet");
}
//sendNotification( new Notification(NOTIF_OPENCONNECTION, NOTIF_OPENCONNECTION,
// notificationSequence++, connection.toString()) );
try {
ConnectionWrapper connection = pool.prepareConnection();
timer.stop("ConnectionPool: getConnection");
// hopefully the common case, we're done!
return connection;
} catch (IndexOutOfBoundsException e) {}
synchronized (pool) {
boolean timeToCreate = false;
do {
// try again now that we're synchronized
if ( pool.connections.size() > 0 ) {
try {
ConnectionWrapper connection = pool.prepareConnection();
timer.stop("ConnectionPool: getConnection");
return connection;
} catch (IndexOutOfBoundsException e) {}
} else if ( pool.connectionCount < pool.getMaxConnections() ) {
timeToCreate = true;
} else {
// Too many connections? Let's wait for some to free up.
if (logger.isDebugEnabled()) {
logger
.debug("getConnection(String) - WARNING: [ConnectionPool] too many connections in use [" + pool.connectionsInUse.size() + "], waiting [" + Thread.currentThread() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
try { pool.wait(); } catch (InterruptedException e) {}
if ( pool.showDebugging() ) {
if (logger.isDebugEnabled()) {
logger
.debug("getConnection(String) - INFO: [ConnectionPool] freed up! [" + Thread.currentThread() + "] connections in use= [" + pool.connectionsInUse.size() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
}
} while ( timeToCreate == false );
// if we made it here, the pool is too small or there are no more
// connections in the pool, time to initialize another
pool.connectionCount++;
}
// Now we're unsynchronzied so others can get a lock on the pool to do their thing.
// We should be safe to open a new connection because we already reserved it by
// doing pool.connectionCount++. But if we fail in getting the new connection, let's
// make sure to pool.connectionCount-- so others can try.
try {
ConnectionWrapper connection = pool.openNewConnection();
timer.stop("ConnectionPool: getConnection");
return connection;
} catch (SQLException e) {
pool.connectionCount--;
timer.stop("ConnectionPool: getConnection");
throw e;
}
}