Package org.apache.tomcat.jdbc.pool
Class ConnectionPool
- java.lang.Object
-
- org.apache.tomcat.jdbc.pool.ConnectionPool
-
public class ConnectionPool extends Object
Implementation of simple connection pool. The ConnectionPool uses aPoolPropertiesobject for storing all the meta information about the connection pool. As the underlying implementation, the connection pool usesBlockingQueueto store active and idle connections. A custom implementation of a fairFairBlockingQueueblocking queue is provided with the connection pool itself.- Version:
- 1.0
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected classConnectionPool.ConnectionFutureTread safe wrapper around a future for the regular queue This one retrieves the pooled connection object and performs the initialization according to interceptors and validation rules.protected static classConnectionPool.PoolCleaner
-
Field Summary
Fields Modifier and Type Field Description protected ConnectionPooljmxPoolreference to the JMX mbeanstatic StringPOOL_JMX_DOMAINDefault domain for objects registering with an mbean serverstatic StringPOOL_JMX_TYPE_PREFIXPrefix type for JMX registration
-
Constructor Summary
Constructors Constructor Description ConnectionPool(PoolConfiguration prop)Instantiate a connection pool.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description protected voidabandon(PooledConnection con)thread safe way to abandon a connection signals a connection to be abandoned.protected PooledConnectionborrowConnection(long now, PooledConnection con, String username, String password)Validates and configures a previously idle connectionvoidcheckAbandoned()Iterates through all the busy connections and checks for connections that have timed outvoidcheckIdle()Iterates through the idle connections and resizes the idle pool based on parametersPoolProperties.maxIdle,PoolProperties.minIdle,PoolProperties.minEvictableIdleTimeMillisvoidcheckIdle(boolean ignoreMinSize)voidcheckPoolConfiguration(PoolConfiguration properties)protected voidclose(boolean force)Closes the pool and all disconnects all idle connections Active connections will be closed upon theclosemethod is called on the underlying connection instead of being returned to the poolprotected PooledConnectioncreate(boolean incrementCounter)Create a new pooled connection object.protected PooledConnectioncreateConnection(long now, PooledConnection notUsed, String username, String password)Creates a JDBC connection and tries to connect to the database.protected voidcreateMBean()Create MBean object that can be registered.protected voiddisconnectEvent(PooledConnection con, boolean finalizing)Hook to perform final actions on a pooled connection object once it has been disconnected and will be discardedprotected voidfinalize(PooledConnection con)Hook to perform final actions on a pooled connection object once it has been disconnected and will be discardedintgetActive()Returns the number of connections that are in uselonggetBorrowedCount()The total number of connections borrowed from this pool.ConnectiongetConnection()Borrows a connection from the pool.ConnectiongetConnection(String username, String password)Borrows a connection from the pool.Future<Connection>getConnectionAsync()Retrieves a Connection future.longgetCreatedCount()The total number of connections created by this pool.intgetIdle()Returns the number of idle connectionsConnectionPoolgetJmxPool()Return the object that is potentially registered in JMX for notificationsStringgetName()Returns the name of this poolstatic Set<TimerTask>getPoolCleaners()PoolConfigurationgetPoolProperties()Returns the pool properties associated with this connection poolstatic TimergetPoolTimer()longgetPoolVersion()Constructor<?>getProxyConstructor(boolean xa)Creates and caches aConstructorused to instantiate the proxy object.longgetReconnectedCount()The total number of connections reconnected by this pool.longgetReleasedCount()The total number of connections released from this pool.longgetReleasedIdleCount()The total number of connections released by eviction.longgetRemoveAbandonedCount()The total number of connections released by remove abandoned.longgetReturnedCount()The total number of connections returned to this pool.intgetSize()Returns the total size of this pool, this includes both busy and idle connectionsstatic StringgetStackTrace(Throwable x)Convert an exception into a Stringprotected static StringgetThreadDump()Creates a stack trace representing the existing thread's current state.intgetWaitCount()Return the number of threads waiting for a connectionprotected voidinit(PoolConfiguration properties)Initialize the connection pool - called from the constructorvoidinitializePoolCleaner(PoolConfiguration properties)booleanisClosed()Returns true ifclosehas been called, and the connection pool is unusablevoidpurge()Purges all connections in the pool.voidpurgeOnReturn()Purges connections when they are returned from the pool.protected booleanreconnectIfExpired(PooledConnection con)Checks whether this connection hasexpiredand tries to reconnect if it has.protected voidrelease(PooledConnection con)thread safe way to release a connectionvoidresetStats()reset the statistics of this pool.protected voidreturnConnection(PooledConnection con)Returns a connection to the pool If the pool is closed, the connection will be released If the connection is not part of the busy queue, it will be released.protected ConnectionsetupConnection(PooledConnection con)configures a pooled connection as a proxy.protected booleanshouldAbandon()Determines if a connection should be abandoned based onPoolProperties.abandonWhenPercentageFullsetting.protected booleanshouldClose(PooledConnection con, int action)Determines if a connection should be closed upon return to the pool.protected booleanshouldReleaseIdle(long now, PooledConnection con, long time)protected voidsuspect(PooledConnection con)Thread safe way to suspect a connection.voidterminatePoolCleaner()protected booleanterminateTransaction(PooledConnection con)Terminate the current transaction for the given connection.voidtestAllIdle()Forces a validation of all idle connections ifPoolProperties.testWhileIdleis set.voidtestAllIdle(boolean checkMaxAgeOnly)Forces a validation of all idle connections ifPoolProperties.testWhileIdleis set.
-
-
-
Field Detail
-
POOL_JMX_DOMAIN
public static final String POOL_JMX_DOMAIN
Default domain for objects registering with an mbean server- See Also:
- Constant Field Values
-
POOL_JMX_TYPE_PREFIX
public static final String POOL_JMX_TYPE_PREFIX
Prefix type for JMX registration- See Also:
- Constant Field Values
-
jmxPool
protected ConnectionPool jmxPool
reference to the JMX mbean
-
-
Constructor Detail
-
ConnectionPool
public ConnectionPool(PoolConfiguration prop) throws SQLException
Instantiate a connection pool. This will create connections if initialSize is larger than 0. ThePoolPropertiesshould not be reused for another connection pool.- Parameters:
prop- PoolProperties - all the properties for this connection pool- Throws:
SQLException- Pool initialization error
-
-
Method Detail
-
getConnectionAsync
public Future<Connection> getConnectionAsync() throws SQLException
Retrieves a Connection future. If a connection is not available, one can block using future.get() until a connection has become available. If a connection is not retrieved, the Future must be cancelled in order for the connection to be returned to the pool.- Returns:
- a Future containing a reference to the connection or the future connection
- Throws:
SQLException- Cannot use asynchronous connect
-
getConnection
public Connection getConnection() throws SQLException
Borrows a connection from the pool. If a connection is available (in the idle queue) or the pool has not reachedmaxActiveconnections a connection is returned immediately. If no connection is available, the pool will attempt to fetch a connection formaxWaitmilliseconds.- Returns:
- Connection - a java.sql.Connection/javax.sql.PooledConnection reflection proxy, wrapping the underlying object.
- Throws:
SQLException- - if the wait times out or a failure occurs creating a connection
-
getConnection
public Connection getConnection(String username, String password) throws SQLException
Borrows a connection from the pool. If a connection is available (in the idle queue) or the pool has not reachedmaxActiveconnections a connection is returned immediately. If no connection is available, the pool will attempt to fetch a connection formaxWaitmilliseconds.- Parameters:
username- The user name to use for the connectionpassword- The password for the connection- Returns:
- Connection - a java.sql.Connection/javax.sql.PooledConnection reflection proxy, wrapping the underlying object.
- Throws:
SQLException- - if the wait times out or a failure occurs creating a connection
-
getName
public String getName()
Returns the name of this pool- Returns:
- String - the name of the pool
-
getWaitCount
public int getWaitCount()
Return the number of threads waiting for a connection- Returns:
- number of threads waiting for a connection
-
getPoolProperties
public PoolConfiguration getPoolProperties()
Returns the pool properties associated with this connection pool- Returns:
- PoolProperties
-
getSize
public int getSize()
Returns the total size of this pool, this includes both busy and idle connections- Returns:
- int - number of established connections to the database
-
getActive
public int getActive()
Returns the number of connections that are in use- Returns:
- int - number of established connections that are being used by the application
-
getIdle
public int getIdle()
Returns the number of idle connections- Returns:
- int - number of established connections not being used
-
isClosed
public boolean isClosed()
Returns true ifclosehas been called, and the connection pool is unusable- Returns:
- boolean
-
setupConnection
protected Connection setupConnection(PooledConnection con) throws SQLException
configures a pooled connection as a proxy. This Proxy implementsConnectionandPooledConnectioninterfaces. All calls onConnectionmethods will be propagated down to the actual JDBC connection except for theConnection.close()method.- Parameters:
con- aPooledConnectionto wrap in a Proxy- Returns:
- a
Connectionobject wrapping a pooled connection. - Throws:
SQLException- if an interceptor can't be configured, if the proxy can't be instantiated
-
getProxyConstructor
public Constructor<?> getProxyConstructor(boolean xa) throws NoSuchMethodException
Creates and caches aConstructorused to instantiate the proxy object. We cache this, since the creation of a constructor is fairly slow.- Parameters:
xa- Use a XA connection- Returns:
- constructor used to instantiate the wrapper object
- Throws:
NoSuchMethodException- Failed to get a constructor
-
close
protected void close(boolean force)
Closes the pool and all disconnects all idle connections Active connections will be closed upon theclosemethod is called on the underlying connection instead of being returned to the pool- Parameters:
force- - true to even close the active connections
-
init
protected void init(PoolConfiguration properties) throws SQLException
Initialize the connection pool - called from the constructor- Parameters:
properties- PoolProperties - properties used to initialize the pool with- Throws:
SQLException- if initialization fails
-
checkPoolConfiguration
public void checkPoolConfiguration(PoolConfiguration properties)
-
initializePoolCleaner
public void initializePoolCleaner(PoolConfiguration properties)
-
terminatePoolCleaner
public void terminatePoolCleaner()
-
abandon
protected void abandon(PooledConnection con)
thread safe way to abandon a connection signals a connection to be abandoned. this will disconnect the connection, and log the stack trace if logAbandoned=true- Parameters:
con- PooledConnection
-
suspect
protected void suspect(PooledConnection con)
Thread safe way to suspect a connection. Similar toabandon(PooledConnection), but instead of actually abandoning the connection, this will log a warning and set the suspect flag on thePooledConnectionif logAbandoned=true- Parameters:
con- PooledConnection
-
release
protected void release(PooledConnection con)
thread safe way to release a connection- Parameters:
con- PooledConnection
-
createConnection
protected PooledConnection createConnection(long now, PooledConnection notUsed, String username, String password) throws SQLException
Creates a JDBC connection and tries to connect to the database.- Parameters:
now- timestamp of when this was callednotUsed- Argument not usedusername- The user name to use for the connectionpassword- The password for the connection- Returns:
- a PooledConnection that has been connected
- Throws:
SQLException- Failed to get a connection
-
borrowConnection
protected PooledConnection borrowConnection(long now, PooledConnection con, String username, String password) throws SQLException
Validates and configures a previously idle connection- Parameters:
now- - timestampcon- - the connection to validate and configureusername- The user name to use for the connectionpassword- The password for the connection- Returns:
- a connection
- Throws:
SQLException- if a validation error happens
-
terminateTransaction
protected boolean terminateTransaction(PooledConnection con)
Terminate the current transaction for the given connection.- Parameters:
con- The connection- Returns:
trueif the connection TX termination succeeded otherwisefalse
-
shouldClose
protected boolean shouldClose(PooledConnection con, int action)
Determines if a connection should be closed upon return to the pool.- Parameters:
con- - the connectionaction- - the validation action that should be performed- Returns:
trueif the connection should be closed
-
reconnectIfExpired
protected boolean reconnectIfExpired(PooledConnection con)
Checks whether this connection hasexpiredand tries to reconnect if it has.- Parameters:
con- PooledConnection- Returns:
- true if the connection was either not expired or expired but reconnecting succeeded, false if reconnecting failed (either because a new connection could not be established or validating the newly created connection failed)
- See Also:
PooledConnection.isMaxAgeExpired()
-
returnConnection
protected void returnConnection(PooledConnection con)
Returns a connection to the pool If the pool is closed, the connection will be released If the connection is not part of the busy queue, it will be released. IfPoolProperties.testOnReturnis set to true it will be validated- Parameters:
con- PooledConnection to be returned to the pool
-
shouldAbandon
protected boolean shouldAbandon()
Determines if a connection should be abandoned based onPoolProperties.abandonWhenPercentageFullsetting.- Returns:
trueif the connection should be abandoned
-
checkAbandoned
public void checkAbandoned()
Iterates through all the busy connections and checks for connections that have timed out
-
checkIdle
public void checkIdle()
Iterates through the idle connections and resizes the idle pool based on parametersPoolProperties.maxIdle,PoolProperties.minIdle,PoolProperties.minEvictableIdleTimeMillis
-
checkIdle
public void checkIdle(boolean ignoreMinSize)
-
shouldReleaseIdle
protected boolean shouldReleaseIdle(long now, PooledConnection con, long time)
-
testAllIdle
public void testAllIdle()
Forces a validation of all idle connections ifPoolProperties.testWhileIdleis set.
-
testAllIdle
public void testAllIdle(boolean checkMaxAgeOnly)
Forces a validation of all idle connections ifPoolProperties.testWhileIdleis set.- Parameters:
checkMaxAgeOnly- whether to only checkPooledConnection.isMaxAgeExpired()but not invokePooledConnection.validate(int)
-
getThreadDump
protected static String getThreadDump()
Creates a stack trace representing the existing thread's current state.- Returns:
- a string object representing the current state.
TODO investigate if we simply should store
Thread.getStackTrace()elements
-
getStackTrace
public static String getStackTrace(Throwable x)
Convert an exception into a String- Parameters:
x- - the throwable- Returns:
- a string representing the stack trace
-
create
protected PooledConnection create(boolean incrementCounter)
Create a new pooled connection object. Not connected nor validated.- Parameters:
incrementCounter-trueto increment the connection count- Returns:
- a pooled connection object
-
purge
public void purge()
Purges all connections in the pool. For connections currently in use, these connections will be purged when returned on the pool. This call also purges connections that are idle and in the pool To only purge used/active connections seepurgeOnReturn()
-
purgeOnReturn
public void purgeOnReturn()
Purges connections when they are returned from the pool. This call does not purge idle connections until they are used. To purge idle connections seepurge()
-
finalize
protected void finalize(PooledConnection con)
Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded- Parameters:
con- The connection
-
disconnectEvent
protected void disconnectEvent(PooledConnection con, boolean finalizing)
Hook to perform final actions on a pooled connection object once it has been disconnected and will be discarded- Parameters:
con- The connectionfinalizing-trueif finalizing the connection
-
getJmxPool
public ConnectionPool getJmxPool()
Return the object that is potentially registered in JMX for notifications- Returns:
- the object implementing the
ConnectionPoolMBeaninterface
-
createMBean
protected void createMBean()
Create MBean object that can be registered.
-
getBorrowedCount
public long getBorrowedCount()
The total number of connections borrowed from this pool.- Returns:
- the borrowed connection count
-
getReturnedCount
public long getReturnedCount()
The total number of connections returned to this pool.- Returns:
- the returned connection count
-
getCreatedCount
public long getCreatedCount()
The total number of connections created by this pool.- Returns:
- the created connection count
-
getReleasedCount
public long getReleasedCount()
The total number of connections released from this pool.- Returns:
- the released connection count
-
getReconnectedCount
public long getReconnectedCount()
The total number of connections reconnected by this pool.- Returns:
- the reconnected connection count
-
getRemoveAbandonedCount
public long getRemoveAbandonedCount()
The total number of connections released by remove abandoned.- Returns:
- the PoolCleaner removed abandoned connection count
-
getReleasedIdleCount
public long getReleasedIdleCount()
The total number of connections released by eviction.- Returns:
- the PoolCleaner evicted idle connection count
-
resetStats
public void resetStats()
reset the statistics of this pool.
-
getPoolVersion
public long getPoolVersion()
-
getPoolTimer
public static Timer getPoolTimer()
-
-