/**
* {@inheritDoc}
*/
public synchronized Connection getConnection() {
if (availableConnections == null) {
throw new DbSqlException("Connection pool is not initialized");
}
if (availableConnections.isEmpty() == false) {
int lastIndex = availableConnections.size() - 1;
ConnectionData existingConnection = availableConnections.get(lastIndex);
availableConnections.remove(lastIndex);
// If conn on available list is closed (e.g., it timed out), then remove it from available list
// and repeat the process of obtaining a conn. Also wake up threads that were waiting for a
// conn because maxConnection limit was reached.
long now = System.currentTimeMillis();
boolean isValid = isConnectionValid(existingConnection, now);
if (isValid == false) {
if (log.isDebugEnabled()) {
log.debug("Pooled connection not valid, resetting");
}
notifyAll(); // freed up a spot for anybody waiting
return getConnection();
} else {
if (log.isDebugEnabled()) {
log.debug("Returning valid pooled connection");
}
busyConnections.add(existingConnection);
existingConnection.lastUsed = now;
return existingConnection.connection;
}
}
if (log.isDebugEnabled()) {
log.debug("No more available connections");
}
// no available connections
if (((availableConnections.size() + busyConnections.size()) < maxConnections) && !connectionPending) {
makeBackgroundConnection();
} else if (!waitIfBusy) {
throw new DbSqlException("Connection limit reached: " + maxConnections);
}
// wait for either a new conn to be established (if you called makeBackgroundConnection) or for
// an existing conn to be freed up.
try {
wait();