Search in sources :

Example 1 with PooledObject

use of org.apache.commons.pool2.PooledObject in project karaf by apache.

the class PooledConnectionFactory method initConnectionsPool.

public void initConnectionsPool() {
    if (this.connectionsPool == null) {
        this.connectionsPool = new GenericKeyedObjectPool<>(new KeyedPooledObjectFactory<ConnectionKey, ConnectionPool>() {

            @Override
            public void activateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
            }

            @Override
            public void destroyObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
                try {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Destroying connection: {}", connection);
                    }
                    connection.getObject().close();
                } catch (Exception e) {
                    LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.", e);
                }
            }

            @Override
            public PooledObject<ConnectionPool> makeObject(ConnectionKey key) throws Exception {
                Connection delegate = createConnection(key);
                ConnectionPool connection = createConnectionPool(delegate);
                connection.setIdleTimeout(getIdleTimeout());
                connection.setExpiryTimeout(getExpiryTimeout());
                connection.setMaximumActiveSessionPerConnection(getMaximumActiveSessionPerConnection());
                connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
                if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) {
                    connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout());
                }
                connection.setUseAnonymousProducers(isUseAnonymousProducers());
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Created new connection: {}", connection);
                }
                return new DefaultPooledObject<>(connection);
            }

            @Override
            public void passivateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) throws Exception {
            }

            @Override
            public boolean validateObject(ConnectionKey key, PooledObject<ConnectionPool> connection) {
                if (connection != null && connection.getObject() != null && connection.getObject().expiredCheck()) {
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Connection has expired: {} and will be destroyed", connection);
                    }
                    return false;
                }
                return true;
            }
        });
        // Set max idle (not max active) since our connections always idle in the pool.
        this.connectionsPool.setMaxIdlePerKey(1);
        // We always want our validate method to control when idle objects are evicted.
        this.connectionsPool.setTestOnBorrow(true);
        this.connectionsPool.setTestWhileIdle(true);
    }
}
Also used : DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) PooledObject(org.apache.commons.pool2.PooledObject) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) Connection(javax.jms.Connection) TopicConnection(javax.jms.TopicConnection) QueueConnection(javax.jms.QueueConnection) KeyedPooledObjectFactory(org.apache.commons.pool2.KeyedPooledObjectFactory) JMSException(javax.jms.JMSException)

Example 2 with PooledObject

use of org.apache.commons.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)

Example 3 with PooledObject

use of org.apache.commons.pool2.PooledObject in project datanucleus-rdbms by datanucleus.

the class GenericKeyedObjectPool method evict.

/**
 * {@inheritDoc}
 * <p>
 * Successive activations of this method examine objects in keyed sub-pools
 * in sequence, cycling through the keys and examining objects in
 * oldest-to-youngest order within the keyed sub-pools.
 */
@Override
public void evict() throws Exception {
    assertOpen();
    if (getNumIdle() == 0) {
        return;
    }
    PooledObject<T> underTest = null;
    EvictionPolicy<T> evictionPolicy = getEvictionPolicy();
    synchronized (evictionLock) {
        EvictionConfig evictionConfig = new EvictionConfig(getMinEvictableIdleTimeMillis(), getSoftMinEvictableIdleTimeMillis(), getMinIdlePerKey());
        boolean testWhileIdle = getTestWhileIdle();
        for (int i = 0, m = getNumTests(); i < m; i++) {
            if (evictionIterator == null || !evictionIterator.hasNext()) {
                if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) {
                    List<K> keyCopy = new ArrayList<K>();
                    Lock readLock = keyLock.readLock();
                    readLock.lock();
                    try {
                        keyCopy.addAll(poolKeyList);
                    } finally {
                        readLock.unlock();
                    }
                    evictionKeyIterator = keyCopy.iterator();
                }
                while (evictionKeyIterator.hasNext()) {
                    evictionKey = evictionKeyIterator.next();
                    ObjectDeque<T> objectDeque = poolMap.get(evictionKey);
                    if (objectDeque == null) {
                        continue;
                    }
                    final Deque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects();
                    evictionIterator = new EvictionIterator(idleObjects);
                    if (evictionIterator.hasNext()) {
                        break;
                    }
                    evictionIterator = null;
                }
            }
            if (evictionIterator == null) {
                // Pools exhausted
                return;
            }
            final Deque<PooledObject<T>> idleObjects;
            try {
                underTest = evictionIterator.next();
                idleObjects = evictionIterator.getIdleObjects();
            } catch (NoSuchElementException nsee) {
                // Object was borrowed in another thread
                // Don't count this as an eviction test so reduce i;
                i--;
                evictionIterator = null;
                continue;
            }
            if (!underTest.startEvictionTest()) {
                // Object was borrowed in another thread
                // Don't count this as an eviction test so reduce i;
                i--;
                continue;
            }
            // User provided eviction policy could throw all sorts of
            // crazy exceptions. Protect against such an exception
            // killing the eviction thread.
            boolean evict;
            try {
                evict = evictionPolicy.evict(evictionConfig, underTest, poolMap.get(evictionKey).getIdleObjects().size());
            } catch (Throwable t) {
                // Slightly convoluted as SwallowedExceptionListener
                // uses Exception rather than Throwable
                PoolUtils.checkRethrow(t);
                swallowException(new Exception(t));
                // Don't evict on error conditions
                evict = false;
            }
            if (evict) {
                destroy(evictionKey, underTest, true);
                destroyedByEvictorCount.incrementAndGet();
            } else {
                if (testWhileIdle) {
                    boolean active = false;
                    try {
                        factory.activateObject(evictionKey, underTest);
                        active = true;
                    } catch (Exception e) {
                        destroy(evictionKey, underTest, true);
                        destroyedByEvictorCount.incrementAndGet();
                    }
                    if (active) {
                        if (!factory.validateObject(evictionKey, underTest)) {
                            destroy(evictionKey, underTest, true);
                            destroyedByEvictorCount.incrementAndGet();
                        } else {
                            try {
                                factory.passivateObject(evictionKey, underTest);
                            } catch (Exception e) {
                                destroy(evictionKey, underTest, true);
                                destroyedByEvictorCount.incrementAndGet();
                            }
                        }
                    }
                }
                if (!underTest.endEvictionTest(idleObjects)) {
                // TODO - May need to add code here once additional
                // states are used
                }
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) NoSuchElementException(java.util.NoSuchElementException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Lock(java.util.concurrent.locks.Lock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) PooledObject(org.datanucleus.store.rdbms.datasource.dbcp2.pool2.PooledObject) NoSuchElementException(java.util.NoSuchElementException)

Example 4 with PooledObject

use of org.apache.commons.pool2.PooledObject in project datanucleus-rdbms by datanucleus.

the class GenericKeyedObjectPool method returnObject.

/**
 * Returns an object to a keyed sub-pool.
 * <p>
 * If {@link #getMaxIdlePerKey() maxIdle} is set to a positive value and the
 * number of idle instances under the given key 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 sub-pool
 * under the given key. 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 SwallowedExceptionListener}.
 *
 * @param key pool key
 * @param obj instance to return to the keyed pool
 *
 * @throws IllegalStateException if an object is returned to the pool that
 *                               was not borrowed from it or if an object is
 *                               returned to the pool multiple times
 */
@Override
public void returnObject(K key, T obj) {
    ObjectDeque<T> objectDeque = poolMap.get(key);
    PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<T>(obj));
    if (p == null) {
        throw new IllegalStateException("Returned object not currently part of this pool");
    }
    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 (once GKOP does this)
        p.markReturning();
    }
    long activeTime = p.getActiveTimeMillis();
    if (getTestOnReturn()) {
        if (!factory.validateObject(key, p)) {
            try {
                destroy(key, p, true);
            } catch (Exception e) {
                swallowException(e);
            }
            if (objectDeque.idleObjects.hasTakeWaiters()) {
                try {
                    addObject(key);
                } catch (Exception e) {
                    swallowException(e);
                }
            }
            updateStatsReturn(activeTime);
            return;
        }
    }
    try {
        factory.passivateObject(key, p);
    } catch (Exception e1) {
        swallowException(e1);
        try {
            destroy(key, p, true);
        } catch (Exception e) {
            swallowException(e);
        }
        if (objectDeque.idleObjects.hasTakeWaiters()) {
            try {
                addObject(key);
            } catch (Exception e) {
                swallowException(e);
            }
        }
        updateStatsReturn(activeTime);
        return;
    }
    if (!p.deallocate()) {
        throw new IllegalStateException("Object has already been returned to this pool");
    }
    int maxIdle = getMaxIdlePerKey();
    LinkedBlockingDeque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects();
    if (isClosed() || maxIdle > -1 && maxIdle <= idleObjects.size()) {
        try {
            destroy(key, p, true);
        } catch (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(key);
        }
    }
    if (hasBorrowWaiters()) {
        reuseCapacity();
    }
    updateStatsReturn(activeTime);
}
Also used : PooledObject(org.datanucleus.store.rdbms.datasource.dbcp2.pool2.PooledObject) PooledObjectState(org.datanucleus.store.rdbms.datasource.dbcp2.pool2.PooledObjectState) NoSuchElementException(java.util.NoSuchElementException)

Example 5 with PooledObject

use of org.apache.commons.pool2.PooledObject in project x-pipe by ctripcorp.

the class NettyKeyedPoolClientFactory method makeObject.

@Override
public PooledObject<NettyClient> makeObject(InetSocketAddress key) throws Exception {
    ChannelFuture f = b.connect(key);
    f.get(connectTimeoutMilli, TimeUnit.MILLISECONDS);
    Channel channel = f.channel();
    logger.debug("[makeObject]{}", channel);
    NettyClient nettyClient = new DefaultNettyClient(channel);
    channel.attr(NettyClientHandler.KEY_CLIENT).set(nettyClient);
    return new DefaultPooledObject<NettyClient>(nettyClient);
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultPooledObject(org.apache.commons.pool2.impl.DefaultPooledObject) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel)

Aggregations

DefaultPooledObject (org.apache.commons.pool2.impl.DefaultPooledObject)8 PooledObject (org.apache.commons.pool2.PooledObject)5 URISyntaxException (java.net.URISyntaxException)4 NoSuchElementException (java.util.NoSuchElementException)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 PooledObjectFactory (org.apache.commons.pool2.PooledObjectFactory)4 GenericObjectPoolConfig (org.apache.commons.pool2.impl.GenericObjectPoolConfig)4 Test (org.junit.Test)4 InvalidURIException (redis.clients.jedis.exceptions.InvalidURIException)4 JedisException (redis.clients.jedis.exceptions.JedisException)4 ArrayList (java.util.ArrayList)3 PooledObject (org.apache.tomcat.dbcp.pool2.PooledObject)3 Jedis (redis.clients.jedis.Jedis)3 JedisPool (redis.clients.jedis.JedisPool)3 JedisConnectionException (redis.clients.jedis.exceptions.JedisConnectionException)3 Channel (io.netty.channel.Channel)2 ChannelFuture (io.netty.channel.ChannelFuture)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2 Lock (java.util.concurrent.locks.Lock)2