Class PooledConnection

java.lang.Object
org.apache.tomcat.jdbc.pool.PooledConnection
All Implemented Interfaces:
PooledConnectionMBean

public class PooledConnection extends Object implements PooledConnectionMBean
Represents a pooled connection and holds a reference to the Connection object
  • Field Details

    • PROP_USER

      public static final String PROP_USER
      Attribute key for the username.
      See Also:
    • PROP_PASSWORD

      public static final String PROP_PASSWORD
      Attribute key for the password.
      See Also:
    • VALIDATE_BORROW

      public static final int VALIDATE_BORROW
      Validate when connection is borrowed flag
      See Also:
    • VALIDATE_RETURN

      public static final int VALIDATE_RETURN
      Validate when connection is returned flag
      See Also:
    • VALIDATE_IDLE

      public static final int VALIDATE_IDLE
      Validate when connection is idle flag
      See Also:
    • VALIDATE_INIT

      public static final int VALIDATE_INIT
      Validate when connection is initialized flag
      See Also:
    • poolProperties

      protected PoolConfiguration poolProperties
      The properties for the connection pool
    • xaConnection

      protected volatile XAConnection xaConnection
      If using a XAConnection underneath. On an XA session this is the pool's XABranchTracker wrapper around the handle the data source returned.
    • parent

      protected ConnectionPool parent
      The parent
  • Constructor Details

    • PooledConnection

      public PooledConnection(PoolConfiguration prop, ConnectionPool parent)
      Constructor
      Parameters:
      prop - - pool properties
      parent - - the parent connection pool
  • Method Details

    • getConnectionVersion

      public long getConnectionVersion()
      Description copied from interface: PooledConnectionMBean
      Returns the connection version: the pool purge generation in force when this pooled connection was created. The pool counter is seeded from Long.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:
      getConnectionVersion in interface PooledConnectionMBean
      Returns:
      the pool purge generation at connection creation
    • checkUser

      @Deprecated public boolean checkUser(String username, String password)
      Deprecated.
      use shouldForceReconnect(String, String) method kept since it was public, to avoid changing interface.
      Parameters:
      username - The user name
      password - The password
      Returns:
      true if the pool does not need to reconnect
    • shouldForceReconnect

      public boolean shouldForceReconnect(String username, String password)
      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 from PoolConfiguration.getUsername()
      password - the password you wish to connect with, pass in null to accept the default username from PoolConfiguration.getPassword()
      Returns:
      true if the pool must reconnect
    • connect

      public void connect() throws SQLException
      Connects the underlying connection to the database.
      Throws:
      SQLException - if the method release() has been called.
      SQLException - if driver instantiation fails
      SQLException - if a call to Driver.connect(String, java.util.Properties) fails.
      SQLException - if default properties are configured and a call to Connection.setAutoCommit(boolean), Connection.setCatalog(String), Connection.setTransactionIsolation(int) or Connection.setReadOnly(boolean) fails.
    • connectUsingDataSource

      protected void connectUsingDataSource() throws SQLException
      Connects using the configured DataSource.
      Throws:
      SQLException - if unable to obtain a connection from the DataSource
    • connectUsingDriver

      protected void connectUsingDriver() throws SQLException
      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: PooledConnectionMBean
      Returns true if the connection has been initialized.
      Specified by:
      isInitialized in interface PooledConnectionMBean
      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 than PoolConfiguration.getMaxAge() milliseconds. false otherwise. When a max age is configured, a connection that currently has no physical session - see getLastConnected() - 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:
      isMaxAgeExpired in interface PooledConnectionMBean
      Returns:
      Returns true if the connection has been connected more than PoolConfiguration.getMaxAge() milliseconds. false otherwise.
    • reconnect

      public void reconnect() throws SQLException
      Issues a call to disconnect(boolean) with the argument false followed by a call to connect()
      Throws:
      SQLException - if the call to connect() fails.
    • reconnectWith

      public void reconnectWith(String username, String password) throws SQLException
      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. Unlike reconnect(), 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 from PoolConfiguration.getUsername()
      password - the password to re-establish the connection with, pass in null to accept the default password from PoolConfiguration.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)
      Returns true if 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:
      true if the connection is valid
    • validate

      public boolean validate(int validateAction, String sql)
      Validates a connection.
      Parameters:
      validateAction - the action used. One of VALIDATE_BORROW, VALIDATE_IDLE, VALIDATE_INIT or VALIDATE_RETURN
      sql - the SQL to be used during validation. If the PoolConfiguration.setInitSQL(String) has been called with a statement and the action is VALIDATE_INIT the 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 Validator is 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 the VALIDATE_INIT execution of the configured init 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
      Returns:
      PoolConfiguration.getMinEvictableIdleTimeMillis()
    • release

      public boolean release()
      This method is called if (Now - timeCheckedIn > getReleaseTime()). It claims the released flag first, so any attempt to connect this cached object again fails per connect(), 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

      public void setStackTrace(String trace)
      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 (see abandonTrace), 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

      public String 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 by System.currentTimeMillis()
    • isSuspect

      public boolean isSuspect()
      Description copied from interface: PooledConnectionMBean
      Returns true if the connection is suspected to be invalid.
      Specified by:
      isSuspect in interface PooledConnectionMBean
      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. An abort() 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 a validation-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 by System.currentTimeMillis()
    • setPoolProperties

      public void setPoolProperties(PoolConfiguration poolProperties)
      Sets the pool configuration for this connection and connection pool. Object is shared with the ConnectionPool

      Every 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 of abandon-timeouts. This timestamp can also be reset by the ResetAbandonedTimer.invoke(Object, java.lang.reflect.Method, Object[])
      Specified by:
      getTimestamp in interface PooledConnectionMBean
      Returns:
      the timestamp of the last pool action as defined by System.currentTimeMillis()
    • isDiscarded

      public boolean isDiscarded()
      Returns the discarded flag.
      Specified by:
      isDiscarded in interface PooledConnectionMBean
      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:
      getLastValidated in interface PooledConnectionMBean
      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

      public PoolConfiguration 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 either PoolConfiguration.isPoolSweeperEnabled() or PoolConfiguration.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 that lock() 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

      public Connection 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 the PooledConnection handle that creates such logical handles is the separate cpdsConnection this class keeps, just as the XA handle is getXAConnection().
      Returns:
      the underlying JDBC connection as it was returned from the JDBC driver
    • getXAConnection

      public XAConnection getXAConnection()
      Returns the underlying XA connection
      Returns:
      the XA connection of this session on an XA pool - the pool's XABranchTracker wrapper 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 to Driver.connect(String, java.util.Properties).
      Specified by:
      getLastConnected in interface PooledConnectionMBean
      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

      public JdbcInterceptor getHandler()
      Returns the first handler in the interceptor chain
      Returns:
      the first interceptor for this connection
    • setHandler

      public void setHandler(JdbcInterceptor handler)
      Sets the interceptor chain handler for this connection.
      Parameters:
      handler - the first interceptor in the chain
    • toString

      public String 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 own Connection's own toString(). 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.
      Overrides:
      toString in class Object
      Returns:
      the credential-safe diagnostic rendering
    • isReleased

      public boolean isReleased()
      Returns true if this connection has been released and wont be reused.
      Specified by:
      isReleased in interface PooledConnectionMBean
      Returns:
      true if the method release() has been called
    • getAttributes

      public HashMap<Object,Object> getAttributes()
      Returns the attributes map for this connection.
      Returns:
      the attributes map
    • 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 (see release()), 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

      public ObjectName getObjectName()
      Returns the JMX ObjectName for this pooled connection.
      Returns:
      the JMX ObjectName or null if not registered
    • clearWarnings

      public void clearWarnings() throws SQLException
      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:
      clearWarnings in interface PooledConnectionMBean
      Throws:
      SQLException - if the driver refuses to clear the warnings
    • isClosed

      public boolean isClosed() throws SQLException
      Returns true if this pooled connection is closed: either it currently has no physical connection or that connection is closed.
      Specified by:
      isClosed in interface PooledConnectionMBean
      Returns:
      true if disconnected or the physical connection is closed
      Throws:
      SQLException - if the physical connection reports a failure
    • getAutoCommit

      public boolean getAutoCommit() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns the current auto-commit mode.
      Specified by:
      getAutoCommit in interface PooledConnectionMBean
      Returns:
      the auto-commit mode
      Throws:
      SQLException - if a database access error occurs
    • getCatalog

      public String getCatalog() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns the current catalog name.
      Specified by:
      getCatalog in interface PooledConnectionMBean
      Returns:
      the catalog name
      Throws:
      SQLException - if a database access error occurs
    • getHoldability

      public int getHoldability() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns the current holdability for ResultSet objects.
      Specified by:
      getHoldability in interface PooledConnectionMBean
      Returns:
      the holdability
      Throws:
      SQLException - if a database access error occurs
    • isReadOnly

      public boolean isReadOnly() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns true if the connection is in read-only mode.
      Specified by:
      isReadOnly in interface PooledConnectionMBean
      Returns:
      true if read-only
      Throws:
      SQLException - if a database access error occurs
    • getSchema

      public String getSchema() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns the current schema name.
      Specified by:
      getSchema in interface PooledConnectionMBean
      Returns:
      the schema name
      Throws:
      SQLException - if a database access error occurs
    • getTransactionIsolation

      public int getTransactionIsolation() throws SQLException
      Description copied from interface: PooledConnectionMBean
      Returns the current transaction isolation level.
      Specified by:
      getTransactionIsolation in interface PooledConnectionMBean
      Returns:
      the transaction isolation level
      Throws:
      SQLException - if a database access error occurs