Search in sources :

Example 1 with PooledObject

use of org.apache.tomcat.dbcp.pool2.PooledObject in project tomcat by apache.

the class GenericObjectPool method returnObject.

/**
     * {@inheritDoc}
     * <p>
     * If {@link #getMaxIdle() maxIdle} is set to a positive value and the
     * number of idle instances has reached this value, the returning instance
     * is destroyed.
     * <p>
     * If {@link #getTestOnReturn() testOnReturn} == true, the returning
     * instance is validated before being returned to the idle instance pool. In
     * this case, if validation fails, the instance is destroyed.
     * <p>
     * Exceptions encountered destroying objects for any reason are swallowed
     * but notified via a
     * {@link org.apache.tomcat.dbcp.pool2.SwallowedExceptionListener}.
     */
@Override
public void returnObject(final T obj) {
    final PooledObject<T> p = allObjects.get(new IdentityWrapper<>(obj));
    if (p == null) {
        if (!isAbandonedConfig()) {
            throw new IllegalStateException("Returned object not currently part of this pool");
        }
        // Object was abandoned and removed
        return;
    }
    synchronized (p) {
        final PooledObjectState state = p.getState();
        if (state != PooledObjectState.ALLOCATED) {
            throw new IllegalStateException("Object has already been returned to this pool or is invalid");
        }
        // Keep from being marked abandoned
        p.markReturning();
    }
    final long activeTime = p.getActiveTimeMillis();
    if (getTestOnReturn()) {
        if (!factory.validateObject(p)) {
            try {
                destroy(p);
            } catch (final Exception e) {
                swallowException(e);
            }
            try {
                ensureIdle(1, false);
            } catch (final Exception e) {
                swallowException(e);
            }
            updateStatsReturn(activeTime);
            return;
        }
    }
    try {
        factory.passivateObject(p);
    } catch (final Exception e1) {
        swallowException(e1);
        try {
            destroy(p);
        } catch (final Exception e) {
            swallowException(e);
        }
        try {
            ensureIdle(1, false);
        } catch (final Exception e) {
            swallowException(e);
        }
        updateStatsReturn(activeTime);
        return;
    }
    if (!p.deallocate()) {
        throw new IllegalStateException("Object has already been returned to this pool or is invalid");
    }
    final int maxIdleSave = getMaxIdle();
    if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) {
        try {
            destroy(p);
        } catch (final Exception e) {
            swallowException(e);
        }
    } else {
        if (getLifo()) {
            idleObjects.addFirst(p);
        } else {
            idleObjects.addLast(p);
        }
        if (isClosed()) {
            // Pool closed while object was being added to idle objects.
            // Make sure the returned object is destroyed rather than left
            // in the idle object pool (which would effectively be a leak)
            clear();
        }
    }
    updateStatsReturn(activeTime);
}
Also used : PooledObjectState(org.apache.tomcat.dbcp.pool2.PooledObjectState) NoSuchElementException(java.util.NoSuchElementException)

Example 2 with PooledObject

use of org.apache.tomcat.dbcp.pool2.PooledObject in project tomcat by apache.

the class CPDSConnectionFactory method makeObject.

@Override
public synchronized PooledObject<PooledConnectionAndInfo> makeObject() {
    PooledConnectionAndInfo pci;
    try {
        PooledConnection pc = null;
        if (_username == null) {
            pc = _cpds.getPooledConnection();
        } else {
            pc = _cpds.getPooledConnection(_username, _password);
        }
        if (pc == null) {
            throw new IllegalStateException("Connection pool data source returned null from getPooledConnection");
        }
        // should we add this object as a listener or the pool.
        // consider the validateObject method in decision
        pc.addConnectionEventListener(this);
        pci = new PooledConnectionAndInfo(pc, _username, _password);
        pcMap.put(pc, pci);
    } catch (final SQLException e) {
        throw new RuntimeException(e.getMessage());
    }
    return new DefaultPooledObject<>(pci);
}
Also used : DefaultPooledObject(org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject) PooledConnection(javax.sql.PooledConnection) SQLException(java.sql.SQLException)

Example 3 with PooledObject

use of org.apache.tomcat.dbcp.pool2.PooledObject in project tomcat by apache.

the class KeyedCPDSConnectionFactory method makeObject.

/**
     * Creates a new {@link PooledConnectionAndInfo} from the given {@link UserPassKey}.
     *
     * @param upkey {@link UserPassKey} containing user credentials
     * @throws SQLException if the connection could not be created.
     * @see org.apache.tomcat.dbcp.pool2.KeyedPooledObjectFactory#makeObject(java.lang.Object)
     */
@Override
public synchronized PooledObject<PooledConnectionAndInfo> makeObject(final UserPassKey upkey) throws Exception {
    PooledConnectionAndInfo pci = null;
    PooledConnection pc = null;
    final String username = upkey.getUsername();
    final String password = upkey.getPassword();
    if (username == null) {
        pc = _cpds.getPooledConnection();
    } else {
        pc = _cpds.getPooledConnection(username, password);
    }
    if (pc == null) {
        throw new IllegalStateException("Connection pool data source returned null from getPooledConnection");
    }
    // should we add this object as a listener or the pool.
    // consider the validateObject method in decision
    pc.addConnectionEventListener(this);
    pci = new PooledConnectionAndInfo(pc, username, password);
    pcMap.put(pc, pci);
    return new DefaultPooledObject<>(pci);
}
Also used : DefaultPooledObject(org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject) PooledConnection(javax.sql.PooledConnection)

Example 4 with PooledObject

use of org.apache.tomcat.dbcp.pool2.PooledObject in project tomcat by apache.

the class PoolableConnectionFactory method makeObject.

@Override
public PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = _connFactory.createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }
    try {
        initializeConnection(conn);
    } catch (final SQLException sqle) {
        // Make sure the connection is closed
        try {
            conn.close();
        } catch (final SQLException ignore) {
        // ignore
        }
        // Rethrow original exception so it is visible to caller
        throw sqle;
    }
    final long connIndex = connectionIndex.getAndIncrement();
    if (poolStatements) {
        conn = new PoolingConnection(conn);
        final GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(maxOpenPreparedStatements);
        if (dataSourceJmxName != null) {
            final StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>((PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(_cacheState);
    }
    // Register this connection with JMX
    ObjectName connJmxName;
    if (dataSourceJmxName == null) {
        connJmxName = null;
    } else {
        connJmxName = new ObjectName(dataSourceJmxName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex);
    }
    final PoolableConnection pc = new PoolableConnection(conn, _pool, connJmxName, _disconnectionSqlCodes, _fastFailValidation);
    pc.setCacheState(_cacheState);
    return new DefaultPooledObject<>(pc);
}
Also used : GenericKeyedObjectPoolConfig(org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig) SQLException(java.sql.SQLException) GenericKeyedObjectPool(org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPool) Connection(java.sql.Connection) ObjectName(javax.management.ObjectName) DefaultPooledObject(org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject)

Example 5 with PooledObject

use of org.apache.tomcat.dbcp.pool2.PooledObject in project jedis by xetorthio.

the class JedisPoolTest method returnResourceDestroysResourceOnException.

@Test
public void returnResourceDestroysResourceOnException() {
    class CrashingJedis extends Jedis {

        @Override
        public void resetState() {
            throw new RuntimeException();
        }
    }
    final AtomicInteger destroyed = new AtomicInteger(0);
    class CrashingJedisPooledObjectFactory implements PooledObjectFactory<Jedis> {

        @Override
        public PooledObject<Jedis> makeObject() throws Exception {
            return new DefaultPooledObject<Jedis>(new CrashingJedis());
        }

        @Override
        public void destroyObject(PooledObject<Jedis> p) throws Exception {
            destroyed.incrementAndGet();
        }

        @Override
        public boolean validateObject(PooledObject<Jedis> p) {
            return true;
        }

        @Override
        public void activateObject(PooledObject<Jedis> p) throws Exception {
        }

        @Override
        public void passivateObject(PooledObject<Jedis> p) throws Exception {
        }
    }
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(1);
    JedisPool pool = new JedisPool(config, hnp.getHost(), hnp.getPort(), 2000, "foobared");
    pool.initPool(config, new CrashingJedisPooledObjectFactory());
    Jedis crashingJedis = pool.getResource();
    try {
        crashingJedis.close();
    } catch (Exception ignored) {
    }
    assertEquals(destroyed.get(), 1);
}
Also used : Jedis(redis.clients.jedis.Jedis) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) PooledObjectFactory(org.apache.commons.pool2.PooledObjectFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PooledObject(org.apache.commons.pool2.PooledObject) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) GenericObjectPoolConfig(org.apache.commons.pool2.impl.GenericObjectPoolConfig) JedisPool(redis.clients.jedis.JedisPool) URISyntaxException(java.net.URISyntaxException) JedisException(redis.clients.jedis.exceptions.JedisException) InvalidURIException(redis.clients.jedis.exceptions.InvalidURIException) JedisExhaustedPoolException(redis.clients.jedis.exceptions.JedisExhaustedPoolException) Test(org.junit.Test)

Aggregations

NoSuchElementException (java.util.NoSuchElementException)3 PooledObject (org.apache.commons.pool2.PooledObject)3 DefaultPooledObject (org.apache.commons.pool2.impl.DefaultPooledObject)3 DefaultPooledObject (org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject)3 URISyntaxException (java.net.URISyntaxException)2 SQLException (java.sql.SQLException)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 PooledConnection (javax.sql.PooledConnection)2 PooledObjectFactory (org.apache.commons.pool2.PooledObjectFactory)2 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)2 PooledObject (org.apache.tomcat.dbcp.pool2.PooledObject)2 PooledObjectState (org.apache.tomcat.dbcp.pool2.PooledObjectState)2 Test (org.junit.Test)2 Jedis (redis.clients.jedis.Jedis)2 JedisPool (redis.clients.jedis.JedisPool)2 InvalidURIException (redis.clients.jedis.exceptions.InvalidURIException)2 JedisException (redis.clients.jedis.exceptions.JedisException)2 Connection (java.sql.Connection)1 ArrayList (java.util.ArrayList)1 Lock (java.util.concurrent.locks.Lock)1