Search in sources :

Example 26 with PooledConnection

use of javax.sql.PooledConnection in project tomcat by apache.

the class CPDSConnectionFactory method connectionErrorOccurred.

/**
     * If a fatal error occurs, close the underlying physical connection so as
     * not to be returned in the future
     */
@Override
public void connectionErrorOccurred(final ConnectionEvent event) {
    final PooledConnection pc = (PooledConnection) event.getSource();
    if (null != event.getSQLException()) {
        System.err.println("CLOSING DOWN CONNECTION DUE TO INTERNAL ERROR (" + event.getSQLException() + ")");
    }
    pc.removeConnectionEventListener(this);
    final PooledConnectionAndInfo pci = pcMap.get(pc);
    if (pci == null) {
        throw new IllegalStateException(NO_KEY_MESSAGE);
    }
    try {
        _pool.invalidateObject(pci);
    } catch (final Exception e) {
        System.err.println("EXCEPTION WHILE DESTROYING OBJECT " + pci);
        e.printStackTrace();
    }
}
Also used : PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException)

Example 27 with PooledConnection

use of javax.sql.PooledConnection in project druid by alibaba.

the class DruidDataSource method recycle.

/**
     * 回收连接
     */
protected void recycle(DruidPooledConnection pooledConnection) throws SQLException {
    final DruidConnectionHolder holder = pooledConnection.getConnectionHolder();
    if (holder == null) {
        LOG.warn("connectionHolder is null");
        return;
    }
    if (//
    logDifferentThread && //
    (!isAsyncCloseConnectionEnable()) && //
    pooledConnection.getOwnerThread() != Thread.currentThread()) {
        LOG.warn("get/close not same thread");
    }
    final Connection physicalConnection = holder.getConnection();
    if (pooledConnection.isTraceEnable()) {
        Object oldInfo = null;
        activeConnectionLock.lock();
        try {
            if (pooledConnection.isTraceEnable()) {
                oldInfo = activeConnections.remove(pooledConnection);
                pooledConnection.setTraceEnable(false);
            }
        } finally {
            activeConnectionLock.unlock();
        }
        if (oldInfo == null) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("remove abandonded failed. activeConnections.size " + activeConnections.size());
            }
        }
    }
    final boolean isAutoCommit = holder.isUnderlyingAutoCommit();
    final boolean isReadOnly = holder.isUnderlyingReadOnly();
    final boolean testOnReturn = this.isTestOnReturn();
    try {
        // check need to rollback?
        if ((!isAutoCommit) && (!isReadOnly)) {
            pooledConnection.rollback();
        }
        // reset holder, restore default settings, clear warnings
        boolean isSameThread = pooledConnection.getOwnerThread() == Thread.currentThread();
        if (!isSameThread) {
            final ReentrantLock lock = pooledConnection.lock;
            lock.lock();
            try {
                holder.reset();
            } finally {
                lock.unlock();
            }
        } else {
            holder.reset();
        }
        if (holder.isDiscard()) {
            return;
        }
        if (testOnReturn) {
            boolean validate = testConnectionInternal(physicalConnection);
            if (!validate) {
                JdbcUtils.close(physicalConnection);
                destroyCount.incrementAndGet();
                lock.lock();
                try {
                    activeCount--;
                    closeCount++;
                } finally {
                    lock.unlock();
                }
                return;
            }
        }
        if (!enable) {
            discardConnection(holder.getConnection());
            return;
        }
        boolean result;
        final long lastActiveTimeMillis = System.currentTimeMillis();
        lock.lockInterruptibly();
        try {
            activeCount--;
            closeCount++;
            result = putLast(holder, lastActiveTimeMillis);
            recycleCount++;
        } finally {
            lock.unlock();
        }
        if (!result) {
            JdbcUtils.close(holder.getConnection());
            LOG.info("connection recyle failed.");
        }
    } catch (Throwable e) {
        holder.clearStatementCache();
        if (!holder.isDiscard()) {
            this.discardConnection(physicalConnection);
            holder.setDiscard(true);
        }
        LOG.error("recyle error", e);
        recycleErrorCount.incrementAndGet();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Connection(java.sql.Connection) PooledConnection(javax.sql.PooledConnection)

Example 28 with PooledConnection

use of javax.sql.PooledConnection in project druid by alibaba.

the class DruidDataSourceTest_getPooledConnection method test_conn.

public void test_conn() throws Exception {
    PooledConnection conn = dataSource.getPooledConnection();
    conn.close();
}
Also used : PooledConnection(javax.sql.PooledConnection) DruidPooledConnection(com.alibaba.druid.pool.DruidPooledConnection)

Example 29 with PooledConnection

use of javax.sql.PooledConnection in project druid by alibaba.

the class DruidDataSourceTest_testOnBorrowFailed method test_conn.

public void test_conn() throws Exception {
    PooledConnection conn = dataSource.getPooledConnection();
    conn.close();
    Assert.assertEquals(1, dataSource.getPoolingCount());
    Assert.assertEquals(2, dataSource.getCreateCount());
    Assert.assertEquals(1, dataSource.getDiscardCount());
    Assert.assertEquals(2, dataSource.getConnectCount());
    Assert.assertEquals(1, dataSource.getCloseCount());
}
Also used : PooledConnection(javax.sql.PooledConnection)

Example 30 with PooledConnection

use of javax.sql.PooledConnection in project voltdb by VoltDB.

the class ManagedPoolDataSource method getConnection.

/**
     * This method will return a valid connection as fast as possible. Here is the sequence of events:
     *
     * <ol>
     *  <li>First it will try to take a ready connection from the pool.</li>
     *  <li>If the pool doesn't have any ready connections this method will check
     *      if the pool has space for new connections. If yes, a new connection is created and inserted
     *      into the pool.</li>
     * <li>If the pool is already at maximum size this method will check for abandoned
     *     connections among the connections given out earlier.
     *     If any of the connections are abandoned it will be reclaimed, reset and
     *     given out.</li>
     * <li>If there are no abandoned connections this method waits until a connection becomes
     *     available in the pool, or until the login time out time has passed (if login timeout set).</li>
     * </ol>
     *
     * This sequence means that the pool will not grow till max size as long as there are available connections
     * in the pool. Only when no connections are available will it spend time creating new connections.
     * In addition it will not spend
     * time reclaiming abandoned connections until it's absolutely necessary. Only when no new connections
     * can be created. Ultimately it only blocks if there really are no available connections,
     * none can be created and none can be reclaimed. Since the
     * pool is passive this is the sequence of events that should give the highest performance possible
     * for giving out connections from the pool.
     *
     * <br/><br/>
     * Perhaps it is faster to reclaim a connection if possible than to create a new one. If so, it would be faster
     * to reclaim existing connections before creating new ones. It may also preserve resources better.
     * However, assuming that there will not often be abandoned connections, that programs most often
     * remember to close them, on the average the reclaim check is only going to be "wasted overhead".
     * It will only rarely result in a usable connection. In that perspective it should be faster
     * to only do the reclaim check when no connections can be created.
     *
     * @throws SQLException
     */
public Connection getConnection() throws SQLException {
    PooledConnection pooledConnection = null;
    synchronized (this) {
        if (!initialized) {
            if (initialSize > maxPoolSize) {
                throw new SQLException("Initial size of " + initialSize + " exceeds max. pool size of " + maxPoolSize);
            }
            logInfo("Pre-initializing " + initialSize + " physical connections");
            for (int i = 0; i < initialSize; i++) {
                connectionsInactive.add(createNewConnection());
            }
            initialized = true;
        }
        long loginTimeoutExpiration = calculateLoginTimeoutExpiration();
        // for a connection when the connection is closed will get an SQLException.
        while (pooledConnection == null) {
            if (this.isPoolClosed) {
                throw new SQLException("The pool is closed. You cannot get anymore connections from it.");
            }
            // 1) Check if any connections available in the pool.
            pooledConnection = dequeueFirstIfAny();
            if (pooledConnection != null) {
                return wrapConnectionAndMarkAsInUse(pooledConnection);
            }
            // 2) Check if the pool has space for new connections and create one if it does.
            if (poolHasSpaceForNewConnections()) {
                pooledConnection = createNewConnection();
                return wrapConnectionAndMarkAsInUse(pooledConnection);
            }
            // check if any connections has timed out. Return one if there are any.
            if (this.sessionTimeout > 0) {
                reclaimAbandonedConnections();
                //check if any connections were closed during the time out check.
                pooledConnection = dequeueFirstIfAny();
                if (pooledConnection != null) {
                    return wrapConnectionAndMarkAsInUse(pooledConnection);
                }
            }
            // 4) wait until a connection becomes available or the login timeout passes (if set).
            doWait(loginTimeoutExpiration);
        }
        return wrapConnectionAndMarkAsInUse(pooledConnection);
    }
}
Also used : PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException)

Aggregations

PooledConnection (javax.sql.PooledConnection)40 SQLException (java.sql.SQLException)21 Connection (java.sql.Connection)14 Test (org.junit.Test)7 Context (javax.naming.Context)4 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)3 ResultSet (java.sql.ResultSet)2 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)2 Statement (java.sql.Statement)2 Iterator (java.util.Iterator)2 XAConnection (javax.sql.XAConnection)2 DefaultPooledObject (org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject)2 DruidPooledConnection (com.alibaba.druid.pool.DruidPooledConnection)1 PrintWriter (java.io.PrintWriter)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 NoSuchElementException (java.util.NoSuchElementException)1 ReentrantLock (java.util.concurrent.locks.ReentrantLock)1 InitialContext (javax.naming.InitialContext)1 ConnectionPoolDataSource (javax.sql.ConnectionPoolDataSource)1