abstract class AbstractPoolBackedDataSource
extends PoolBackedDataSourceBase
implements PooledDataSource{
//.....
// dataSource.getConnection()所调用的就是该方法
//implementation of javax.sql.DataSource
public Connection getConnection() throws SQLException{
PooledConnection pc =
getPoolManager(). // 返回 C3P0PooledConnectionPoolManager
getPool(). // 返回 C3P0PooledConnectionPool
checkoutPooledConnection(); // 返回PooledConnection
return pc.getConnection();
}
//.....
}
class C3P0PooledConnectionPool{
// ....
public PooledConnection checkoutPooledConnection() throws SQLException{
//System.err.println(this + " -- CHECKOUT");
try
{
PooledConnection pc = (PooledConnection) this.checkoutAndMarkConnectionInUse();
pc.addConnectionEventListener( cl );
return pc;
}
catch (TimeoutException e)
{ throw SqlUtils.toSQLException("An attempt by a client to checkout a Connection has timed out.", e); }
catch (CannotAcquireResourceException e)
{ throw SqlUtils.toSQLException("Connections could not be acquired from the underlying database!", "08001", e); }
catch (Exception e)
{ throw SqlUtils.toSQLException(e); }
}
private Object checkoutAndMarkConnectionInUse() throws TimeoutException, CannotAcquireResourceException, ResourcePoolException, InterruptedException
{
Object out = null;
boolean success = false;
while (! success)
{
try
{
out = rp.checkoutResource( checkoutTimeout );
if (out instanceof AbstractC3P0PooledConnection)
{
// cast should succeed, because effectiveStatementCache implies c3p0 pooled Connections
AbstractC3P0PooledConnection acpc = (AbstractC3P0PooledConnection) out;
/*
*以下在获取物理连接的时候,PooledcConnection中注册的事件监听器会收到消息
*无论每次对connection的何种操作,PooledConnection都会收到来自驱动的消息,
*其中的钩子(hook)对象就会完成对Connection的回收
*/
Connection physicalConnection = acpc.getPhysicalConnection();
success = tryMarkPhysicalConnectionInUse(physicalConnection);
}
else
success = true; //we don't pool statements from non-c3p0 PooledConnections
}
finally
{
try { if (!success && out != null) rp.checkinResource( out );}
catch (Exception e) { logger.log(MLevel.WARNING, "Failed to check in a Connection that was unusable due to pending Statement closes.", e); }
}
}
return out;
}
//....
}