Class PooledConnection
- All Implemented Interfaces:
PooledConnectionMBean
Connection object-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected ConnectionPoolThe parentprotected PoolConfigurationThe properties for the connection poolstatic final StringAttribute key for the password.static final StringAttribute key for the username.static final intValidate when connection is borrowed flagstatic final intValidate when connection is idle flagstatic final intValidate when connection is initialized flagstatic final intValidate when connection is returned flagprotected XAConnectionIf using a XAConnection underneath. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionbooleanDeprecated.voidClears the warnings on the physical connection.voidconnect()Connects the underlying connection to the database.protected voidConnects using the configured DataSource.protected voidConnects using the configured JDBC Driver class.voidCreates and registers an MBean for this pooled connection with JMX.longReturns abandon timeout in millisecondsReturns the attributes map for this connection.booleanReturns the current auto-commit mode.Returns the current catalog name.Returns the underlying connection: the session the pool established for this entry, not a logical handle created on demand.longReturns the connection version: the pool purge generation in force when this pooled connection was created.Returns the first handler in the interceptor chainintReturns the current holdability for ResultSet objects.longReturns the timestamp of when the connection was last connected to the database, ie, a successful call toDriver.connect(String, java.util.Properties).longReturns the timestamp at which the last successful validation completed on the current physical session.Returns the JMX ObjectName for this pooled connection.Returns the configuration for this connection and poollongThe time limit for how long the object can remain unused before it is releasedReturns the current schema name.Returns the stack trace from when this connection was borrowed.longReturn the timestamps of last pool action.intReturns the current transaction isolation level.Returns the underlying XA connectionbooleanisClosed()Returns true if this pooled connection is closed: either it currently has no physical connection or that connection is closed.booleanReturns the discarded flag.booleanReturns true if the connection has been initialized.booleanReturns true if the connection has been connected more thanPoolConfiguration.getMaxAge()milliseconds. false otherwise.booleanReturns true if the connection is in read-only mode.booleanReturns true if this connection has been released and wont be reused.booleanReturns true if the connection is suspected to be invalid.voidlock()Locks the connection only if eitherPoolConfiguration.isPoolSweeperEnabled()orPoolConfiguration.getUseLock()return true.voidIssues a call todisconnect(boolean)with the argument false followed by a call toconnect()voidreconnectWith(String username, String password) Re-establishes this connection under the credentials handed in, giving up the session it currently holds only once a session established under those credentials has been opened.booleanrelease()This method is called if (Now - timeCheckedIn > getReleaseTime()).voidsetDiscarded(boolean discarded) An interceptor can call this method with the value true, and the connection will be closed when it is returned to the pool.voidsetHandler(JdbcInterceptor handler) Sets the interceptor chain handler for this connection.voidsetLastValidated(long lastValidated) Set the timestamp the connection was last validated.voidsetPoolProperties(PoolConfiguration poolProperties) Sets the pool configuration for this connection and connection pool.voidsetStackTrace(String trace) Replaces the abandoned-connection trace.voidsetSuspect(boolean suspect) Sets the suspect flag for this connection.voidsetTimestamp(long timestamp) Sets a timestamp on this connection.booleanshouldForceReconnect(String username, String password) Returns true if we must force reconnect based on credentials passed in.toString()Returns a diagnostic rendering of this pooled connection that is safe to interpolate into a pool log message: the connection's identity and whether it currently holds a physical session, never the driver's ownConnection's owntoString().voidunlock()Unlocks the connection if, and only if, this thread currently holds the lock.voidReleases the MBeans published for this connection and for the interceptors of its chain, without releasing the physical session.booleanvalidate(int validateAction) Returnstrueif the object is still valid.booleanValidates a connection.
-
Field Details
-
PROP_USER
-
PROP_PASSWORD
-
VALIDATE_BORROW
public static final int VALIDATE_BORROWValidate when connection is borrowed flag- See Also:
-
VALIDATE_RETURN
public static final int VALIDATE_RETURNValidate when connection is returned flag- See Also:
-
VALIDATE_IDLE
public static final int VALIDATE_IDLEValidate when connection is idle flag- See Also:
-
VALIDATE_INIT
public static final int VALIDATE_INITValidate when connection is initialized flag- See Also:
-
poolProperties
The properties for the connection pool -
xaConnection
If using a XAConnection underneath. On an XA session this is the pool'sXABranchTrackerwrapper around the handle the data source returned. -
parent
The parent
-
-
Constructor Details
-
PooledConnection
Constructor- Parameters:
prop- - pool propertiesparent- - the parent connection pool
-
-
Method Details
-
getConnectionVersion
public long getConnectionVersion()Description copied from interface:PooledConnectionMBeanReturns the connection version: the pool purge generation in force when this pooled connection was created. The pool counter is seeded fromLong.MIN_VALUE, so a connection created against a freshly started pool reports a large negative number; it is not a connection age and not a version of the driver. Connections older than the pool's current generation are retired by the pool as they are used or swept.- Specified by:
getConnectionVersionin interfacePooledConnectionMBean- Returns:
- the pool purge generation at connection creation
-
checkUser
Deprecated.useshouldForceReconnect(String, String)method kept since it was public, to avoid changing interface.- Parameters:
username- The user namepassword- The password- Returns:
trueif the pool does not need to reconnect
-
shouldForceReconnect
Returns true if we must force reconnect based on credentials passed in. Returns false if the username/password has not changed since this connection was connected. This is a comparison only; the identity a session is established with is written by the reconnect that follows the decision.- Parameters:
username- the username you wish to connect with, pass in null to accept the default username fromPoolConfiguration.getUsername()password- the password you wish to connect with, pass in null to accept the default username fromPoolConfiguration.getPassword()- Returns:
- true if the pool must reconnect
-
connect
Connects the underlying connection to the database.- Throws:
SQLException- if the methodrelease()has been called.SQLException- if driver instantiation failsSQLException- if a call toDriver.connect(String, java.util.Properties)fails.SQLException- if default properties are configured and a call toConnection.setAutoCommit(boolean),Connection.setCatalog(String),Connection.setTransactionIsolation(int)orConnection.setReadOnly(boolean)fails.
-
connectUsingDataSource
Connects using the configured DataSource.- Throws:
SQLException- if unable to obtain a connection from the DataSource
-
connectUsingDriver
Connects using the configured JDBC Driver class.- Throws:
SQLException- if unable to instantiate the driver or obtain a connection
-
isInitialized
public boolean isInitialized()Description copied from interface:PooledConnectionMBeanReturns true if the connection has been initialized.- Specified by:
isInitializedin interfacePooledConnectionMBean- Returns:
- true if connect() was called successfully and disconnect has not yet been called
-
isMaxAgeExpired
public boolean isMaxAgeExpired()Returns true if the connection has been connected more thanPoolConfiguration.getMaxAge()milliseconds. false otherwise. When a max age is configured, a connection that currently has no physical session - seegetLastConnected()- also returns true, as a session that is not connected is never young enough to keep; without a configured max age this method always returns false.- Specified by:
isMaxAgeExpiredin interfacePooledConnectionMBean- Returns:
- Returns true if the connection has been connected more than
PoolConfiguration.getMaxAge()milliseconds. false otherwise.
-
reconnect
Issues a call todisconnect(boolean)with the argument false followed by a call toconnect()- Throws:
SQLException- if the call toconnect()fails.
-
reconnectWith
Re-establishes this connection under the credentials handed in, giving up the session it currently holds only once a session established under those credentials has been opened. Unlikereconnect(), a refused credential change therefore leaves the healthy session in place. The staged credentials are restored if the attempt fails.- Parameters:
username- the username to re-establish the connection with, pass in null to accept the default username fromPoolConfiguration.getUsername()password- the password to re-establish the connection with, pass in null to accept the default password fromPoolConfiguration.getPassword()- Throws:
SQLException- if the database refused the credentials or a session under them could not be established. This connection then still holds the session, and carries the credentials, it held before the call.
-
getAbandonTimeout
public long getAbandonTimeout()Returns abandon timeout in milliseconds- Returns:
- abandon timeout in milliseconds
-
validate
public boolean validate(int validateAction) Returnstrueif the object is still valid. A false answer is the caller's cue to stop trusting this session: a newly established connection that fails its check is released rather than pooled, a borrow whose check fails is re-established before it is served, and an idle sweep that reports failure takes the connection out of service.- Parameters:
validateAction- The value- Returns:
trueif the connection is valid
-
validate
Validates a connection.- Parameters:
validateAction- the action used. One ofVALIDATE_BORROW,VALIDATE_IDLE,VALIDATE_INITorVALIDATE_RETURNsql- the SQL to be used during validation. If thePoolConfiguration.setInitSQL(String)has been called with a statement and the action isVALIDATE_INITthe init SQL will be used for validation, and a blank argument, like a blank configured statement, reads as no statement. Whether anything runs at all is the action's own configuration that decides: for an action the pool has not enabled, this method returns true without executing the statement or touching the connection.- Returns:
- true if the connection was validated successfully. It returns true even if validation was not performed,
such as when
PoolConfiguration.setValidationInterval(long)has been called with a positive value.false if the validation failed. The caller should close the connection if false is returned since a session could have been left in an unknown state during initialization. A connection that was never connected, or has already been disconnected, is always reported as invalid.
A validation that runs its built-in check against the database also ends any transaction that is open on the session when the check completes - a pool configured with a custom
Validatoris not, as the validator replaces the check and owns the session state it observes. The transaction ended is the one the check itself may have started, or one a previous borrower left open. A read-only check is ended with a rollback, never with a commit: a pool health check must not commit application work the application itself never committed. The one exception is theVALIDATE_INITexecution of the configuredinit SQL: that query is not a check but the pool's own initialization of the session it has just established, so its transaction is ended with a commit and the initialization persists for the connection's lifetime. When the transaction cannot be ended - by the commit or by the rollback - the session state is unknown, so the validation is reported as failed and the pool takes the connection out of service.
-
getReleaseTime
public long getReleaseTime()The time limit for how long the object can remain unused before it is released -
release
public boolean release()This method is called if (Now - timeCheckedIn > getReleaseTime()). It claims thereleasedflag first, so any attempt to connect this cached object again fails perconnect(), and then disconnects the connection; a failure of the disconnect itself is logged. Only the call that settles the flag drives the disconnection, and later calls return without touching the session. The connection pool uses the atomic return value to decrement the pool size counter.- Returns:
- true if this is the first time this method has been called. false if this method has been called before.
-
setStackTrace
Replaces the abandoned-connection trace. The pool itself only ever clears it - the return path hands the session back with a null trace so no report can read the finished borrow's site - and a non-null value is the externally supplied form of the trace, kept public for that use. Either way the value lands in the same slot the borrow-site frames live in (seeabandonTrace), so a hand-written trace is replaced by the next borrow's site just like a recorded one is.- Parameters:
trace- the stack trace for this connection, or null to clear it
-
getStackTrace
Returns the stack trace from when this connection was borrowed. Can return null if no stack trace was set.- Returns:
- the stack trace or null of no trace was set
-
setTimestamp
public void setTimestamp(long timestamp) Sets a timestamp on this connection. A timestamp usually means that some operation performed successfully.- Parameters:
timestamp- the timestamp as defined bySystem.currentTimeMillis()
-
isSuspect
public boolean isSuspect()Description copied from interface:PooledConnectionMBeanReturns true if the connection is suspected to be invalid.- Specified by:
isSuspectin interfacePooledConnectionMBean- Returns:
- true if suspect
-
setSuspect
public void setSuspect(boolean suspect) Sets the suspect flag for this connection.- Parameters:
suspect- true if the connection is suspected to be invalid
-
setDiscarded
public void setDiscarded(boolean discarded) An interceptor can call this method with the value true, and the connection will be closed when it is returned to the pool. Anabort()on a handle to this connection completes the discard immediately rather than waiting for the return.- Parameters:
discarded- - only valid value is true- Throws:
IllegalStateException- if this method is called with the value false and the value true has already been set.
-
setLastValidated
public void setLastValidated(long lastValidated) Set the timestamp the connection was last validated. This flag is used to keep track when we are using avalidation-interval.The pool stamps this itself as each of its own validations completes; writing it by hand suppresses the checks the interval would otherwise run for up to that interval, which makes the setter a surface for tests and for an embedder driving that bookkeeping directly rather than a way to operate a running pool.
- Parameters:
lastValidated- a timestamp as defined bySystem.currentTimeMillis()
-
setPoolProperties
Sets the pool configuration for this connection and connection pool. Object is shared with theConnectionPoolEvery connection of a pool reads the same configuration object, and the pool builds each connection against the one it was created with; replacing the reference here therefore changes what this single connection sees while the rest of the pool keeps reading the old configuration. That makes the setter a surface for tests and for an embedder that owns the wiring, not a way to reconfigure a running pool.
DataSourceProxy.setPoolProperties(PoolConfiguration)likewise affects only a pool created afterwards; a live pool keeps the configuration it was built from.- Parameters:
poolProperties- The pool properties
-
getTimestamp
public long getTimestamp()Return the timestamps of last pool action. Timestamps are typically set when connections are borrowed from the pool. It is used to keep track ofabandon-timeouts. This timestamp can also be reset by theResetAbandonedTimer.invoke(Object, java.lang.reflect.Method, Object[])- Specified by:
getTimestampin interfacePooledConnectionMBean- Returns:
- the timestamp of the last pool action as defined by
System.currentTimeMillis()
-
isDiscarded
public boolean isDiscarded()Returns the discarded flag.- Specified by:
isDiscardedin interfacePooledConnectionMBean- Returns:
- the discarded flag. If the value is true, either
disconnect(boolean)has been called or it will be called when the connection is returned to the pool.
-
getLastValidated
public long getLastValidated()Returns the timestamp at which the last successful validation completed on the current physical session. While the session has not been validated it reports 0, so a validation inherited from the session a reconnect replaced cannot be mistaken for one of this session. Before any session has been established, it reports the time this pooled connection was created.- Specified by:
getLastValidatedin interfacePooledConnectionMBean- Returns:
- the timestamp at which the last successful validation completed as defined by
System.currentTimeMillis(), or 0 while the current session has not been validated
-
getPoolProperties
Returns the configuration for this connection and pool- Returns:
- the configuration for this connection and pool
-
lock
public void lock()Locks the connection only if eitherPoolConfiguration.isPoolSweeperEnabled()orPoolConfiguration.getUseLock()return true. The per connection lock ensures thread safety if multiple threads are performing operations on the connection. Otherwise this is a noop for performance -
unlock
public void unlock()Unlocks the connection if, and only if, this thread currently holds the lock. The release decision is based on the lock state rather than on the configuration thatlock()consulted, because that configuration is mutable (it can be changed at runtime through JMX) and may differ between the two calls: deciding by configuration would either leave the lock write-locked forever (enabled at lock() time, disabled at unlock() time) or throw IllegalMonitorStateException (disabled at lock() time, enabled at unlock() time). -
getConnection
Returns the underlying connection: the session the pool established for this entry, not a logical handle created on demand. On a CPDS-configured pool thePooledConnectionhandle that creates such logical handles is the separatecpdsConnectionthis class keeps, just as the XA handle isgetXAConnection().- Returns:
- the underlying JDBC connection as it was returned from the JDBC driver
-
getXAConnection
Returns the underlying XA connection- Returns:
- the XA connection of this session on an XA pool - the pool's
XABranchTrackerwrapper around the handle that the data source returned, which delegates every call to it - or null when the pool is not backed by an XA data source or this session has been disconnected
-
getLastConnected
public long getLastConnected()Returns the timestamp of when the connection was last connected to the database, ie, a successful call toDriver.connect(String, java.util.Properties).- Specified by:
getLastConnectedin interfacePooledConnectionMBean- Returns:
- the timestamp of the last successful connection as defined by
System.currentTimeMillis(), or -1 when this pooled connection currently has no physical session - never connected, disconnected, or mid-reconnect
-
getHandler
Returns the first handler in the interceptor chain- Returns:
- the first interceptor for this connection
-
setHandler
Sets the interceptor chain handler for this connection.- Parameters:
handler- the first interceptor in the chain
-
toString
Returns a diagnostic rendering of this pooled connection that is safe to interpolate into a pool log message: the connection's identity and whether it currently holds a physical session, never the driver's ownConnection's owntoString(). That text is unmasked and may carry the URL, the user or other session details, and it may contain newlines, so passing it into a pool warning could expose a credential or forge log lines. A caller that wants the driver's text for an explicit dump can read the physical connection itself. -
isReleased
public boolean isReleased()Returns true if this connection has been released and wont be reused.- Specified by:
isReleasedin interfacePooledConnectionMBean- Returns:
- true if the method
release()has been called
-
getAttributes
-
createMBean
public void createMBean()Creates and registers an MBean for this pooled connection with JMX. The pool's own MBean is the registration base; once close() has given it up - which a borrow can race - there is no base to register under, and the registration is skipped. It is skipped as well for a connection that is already registered - the pool reaches a live connection from the connect path and from the sweep it runs when its own MBean is published - and for a released one, which would leave a registration of a dead connection behind with nothing left to unregister it. The check and the publish are one synchronized step because those paths can meet on the same connection and must never publish it twice: only one of the registrations would ever be unregistered. The release of a connection settles its unregistration and its released flag under this same monitor (seerelease()), so whichever of the two passes first settles the outcome: a registration after a release sees the released flag and publishes nothing, and a release after a registration finds the name and takes it back. -
unregisterMBean
public void unregisterMBean()Releases the MBeans published for this connection and for the interceptors of its chain, without releasing the physical session. The pool uses this when its own MBean is released while the pool stays live: the connection and its chain remain usable, and a later borrow or reconnect can publish them again. -
getObjectName
Returns the JMX ObjectName for this pooled connection.- Returns:
- the JMX ObjectName or null if not registered
-
clearWarnings
Clears the warnings on the physical connection. A no-op while this pooled connection has no physical connection, as there is nothing to clear warnings on. Like the delegating getters below, this operation is best effort against the live session: it does not take the per-connection lock, and the session it reaches may be in use by a borrower or by the pool's own work.- Specified by:
clearWarningsin interfacePooledConnectionMBean- Throws:
SQLException- if the driver refuses to clear the warnings
-
isClosed
Returns true if this pooled connection is closed: either it currently has no physical connection or that connection is closed.- Specified by:
isClosedin interfacePooledConnectionMBean- Returns:
- true if disconnected or the physical connection is closed
- Throws:
SQLException- if the physical connection reports a failure
-
getAutoCommit
Description copied from interface:PooledConnectionMBeanReturns the current auto-commit mode.- Specified by:
getAutoCommitin interfacePooledConnectionMBean- Returns:
- the auto-commit mode
- Throws:
SQLException- if a database access error occurs
-
getCatalog
Description copied from interface:PooledConnectionMBeanReturns the current catalog name.- Specified by:
getCatalogin interfacePooledConnectionMBean- Returns:
- the catalog name
- Throws:
SQLException- if a database access error occurs
-
getHoldability
Description copied from interface:PooledConnectionMBeanReturns the current holdability for ResultSet objects.- Specified by:
getHoldabilityin interfacePooledConnectionMBean- Returns:
- the holdability
- Throws:
SQLException- if a database access error occurs
-
isReadOnly
Description copied from interface:PooledConnectionMBeanReturns true if the connection is in read-only mode.- Specified by:
isReadOnlyin interfacePooledConnectionMBean- Returns:
- true if read-only
- Throws:
SQLException- if a database access error occurs
-
getSchema
Description copied from interface:PooledConnectionMBeanReturns the current schema name.- Specified by:
getSchemain interfacePooledConnectionMBean- Returns:
- the schema name
- Throws:
SQLException- if a database access error occurs
-
getTransactionIsolation
Description copied from interface:PooledConnectionMBeanReturns the current transaction isolation level.- Specified by:
getTransactionIsolationin interfacePooledConnectionMBean- Returns:
- the transaction isolation level
- Throws:
SQLException- if a database access error occurs
-
shouldForceReconnect(String, String)method kept since it was public, to avoid changing interface.