Class PooledConnection

  • All Implemented Interfaces:
    PooledConnectionMBean

    public class PooledConnection
    extends java.lang.Object
    implements PooledConnectionMBean
    Represents a pooled connection and holds a reference to the Connection object
    • Method Summary

      All Methods Instance Methods Concrete Methods Deprecated Methods 
      Modifier and Type Method Description
      boolean checkUser​(java.lang.String username, java.lang.String password)
      Deprecated.
      use shouldForceReconnect(String, String) method kept since it was public, to avoid changing interface.
      void clearWarnings()
      Clears the warnings on the physical connection.
      void connect()
      Connects the underlying connection to the database.
      protected void connectUsingDataSource()
      Connects using the configured DataSource.
      protected void connectUsingDriver()
      Connects using the configured JDBC Driver class.
      void createMBean()
      Creates and registers an MBean for this pooled connection with JMX.
      long getAbandonTimeout()
      Returns abandon timeout in milliseconds
      java.util.HashMap<java.lang.Object,​java.lang.Object> getAttributes()
      Returns the attributes map for this connection.
      boolean getAutoCommit()
      Returns the current auto-commit mode.
      java.lang.String getCatalog()
      Returns the current catalog name.
      java.sql.Connection getConnection()
      Returns the underlying connection: the session the pool established for this entry, not a logical handle created on demand.
      long getConnectionVersion()
      Returns the connection version: the pool purge generation in force when this pooled connection was created.
      JdbcInterceptor getHandler()
      Returns the first handler in the interceptor chain
      int getHoldability()
      Returns the current holdability for ResultSet objects.
      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).
      long getLastValidated()
      Returns the timestamp at which the last successful validation completed on the current physical session.
      javax.management.ObjectName getObjectName()
      Returns the JMX ObjectName for this pooled connection.
      PoolConfiguration getPoolProperties()
      Returns the configuration for this connection and pool
      long getReleaseTime()
      The time limit for how long the object can remain unused before it is released
      java.lang.String getSchema()
      Returns the current schema name.
      java.lang.String getStackTrace()
      Returns the stack trace from when this connection was borrowed.
      long getTimestamp()
      Return the timestamps of last pool action.
      int getTransactionIsolation()
      Returns the current transaction isolation level.
      javax.sql.XAConnection getXAConnection()
      Returns the underlying XA connection
      boolean isClosed()
      Returns true if this pooled connection is closed: either it currently has no physical connection or that connection is closed.
      boolean isDiscarded()
      Returns the discarded flag.
      boolean isInitialized()
      Returns true if the connection has been initialized.
      boolean isMaxAgeExpired()
      Returns true if the connection has been connected more than PoolConfiguration.getMaxAge() milliseconds.
      boolean isReadOnly()
      Returns true if the connection is in read-only mode.
      boolean isReleased()
      Returns true if this connection has been released and wont be reused.
      boolean isSuspect()
      Returns true if the connection is suspected to be invalid.
      void lock()
      Locks the connection only if either PoolConfiguration.isPoolSweeperEnabled() or PoolConfiguration.getUseLock() return true.
      void reconnect()
      Issues a call to disconnect(boolean) with the argument false followed by a call to connect()
      void reconnectWith​(java.lang.String username, java.lang.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.
      boolean release()
      This method is called if (Now - timeCheckedIn > getReleaseTime()).
      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.
      void setHandler​(JdbcInterceptor handler)
      Sets the interceptor chain handler for this connection.
      void setLastValidated​(long lastValidated)
      Set the timestamp the connection was last validated.
      void setPoolProperties​(PoolConfiguration poolProperties)
      Sets the pool configuration for this connection and connection pool.
      void setStackTrace​(java.lang.String trace)
      Replaces the abandoned-connection trace.
      void setSuspect​(boolean suspect)
      Sets the suspect flag for this connection.
      void setTimestamp​(long timestamp)
      Sets a timestamp on this connection.
      boolean shouldForceReconnect​(java.lang.String username, java.lang.String password)
      Returns true if we must force reconnect based on credentials passed in.
      java.lang.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().
      void unlock()
      Unlocks the connection if, and only if, this thread currently holds the lock.
      void unregisterMBean()
      Releases the MBeans published for this connection and for the interceptors of its chain, without releasing the physical session.
      boolean validate​(int validateAction)
      Returns true if the object is still valid.
      boolean validate​(int validateAction, java.lang.String sql)
      Validates a connection.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Field Detail

      • PROP_USER

        public static final java.lang.String PROP_USER
        Attribute key for the username.
        See Also:
        Constant Field Values
      • PROP_PASSWORD

        public static final java.lang.String PROP_PASSWORD
        Attribute key for the password.
        See Also:
        Constant Field Values
      • VALIDATE_BORROW

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

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

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

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

        protected PoolConfiguration poolProperties
        The properties for the connection pool
      • xaConnection

        protected volatile javax.sql.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.
    • Constructor Detail

      • PooledConnection

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

      • 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​(java.lang.String username,
                                 java.lang.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​(java.lang.String username,
                                            java.lang.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 java.sql.SQLException
        Connects the underlying connection to the database.
        Throws:
        java.sql.SQLException - if the method release() has been called.
        java.sql.SQLException - if driver instantiation fails
        java.sql.SQLException - if a call to Driver.connect(String, java.util.Properties) fails.
        java.sql.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 java.sql.SQLException
        Connects using the configured DataSource.
        Throws:
        java.sql.SQLException - if unable to obtain a connection from the DataSource
      • connectUsingDriver

        protected void connectUsingDriver()
                                   throws java.sql.SQLException
        Connects using the configured JDBC Driver class.
        Throws:
        java.sql.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 java.sql.SQLException
        Issues a call to disconnect(boolean) with the argument false followed by a call to connect()
        Throws:
        java.sql.SQLException - if the call to connect() fails.
      • reconnectWith

        public void reconnectWith​(java.lang.String username,
                                  java.lang.String password)
                           throws java.sql.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:
        java.sql.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,
                                java.lang.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.

      • 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​(java.lang.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 java.lang.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()
      • 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:
        java.lang.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
      • 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
      • 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 java.sql.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 javax.sql.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 java.lang.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 java.lang.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 java.util.HashMap<java.lang.Object,​java.lang.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 javax.management.ObjectName getObjectName()
        Returns the JMX ObjectName for this pooled connection.
        Returns:
        the JMX ObjectName or null if not registered
      • clearWarnings

        public void clearWarnings()
                           throws java.sql.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:
        java.sql.SQLException - if the driver refuses to clear the warnings
      • isClosed

        public boolean isClosed()
                         throws java.sql.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:
        java.sql.SQLException - if the physical connection reports a failure
      • getAutoCommit

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

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

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

        public boolean isReadOnly()
                           throws java.sql.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:
        java.sql.SQLException - if a database access error occurs
      • getSchema

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

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