Example usage for org.apache.commons.pool.impl GenericObjectPool setMaxIdle

List of usage examples for org.apache.commons.pool.impl GenericObjectPool setMaxIdle

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool setMaxIdle.

Prototype

public synchronized void setMaxIdle(int maxIdle) 

Source Link

Document

Sets the cap on the number of "idle" instances in the pool.

Usage

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testEvictionSoftMinIdle() throws Exception {
    GenericObjectPool pool = null;

    class TimeTest extends BasePoolableObjectFactory {
        private final long createTime;

        public TimeTest() {
            createTime = System.currentTimeMillis();
        }//  w w  w.  jav a2  s .  c  om

        public Object makeObject() throws Exception {
            return new TimeTest();
        }

        public long getCreateTime() {
            return createTime;
        }
    }

    pool = new GenericObjectPool(new TimeTest());

    pool.setMaxIdle(5);
    pool.setMaxActive(5);
    pool.setNumTestsPerEvictionRun(5);
    pool.setMinEvictableIdleTimeMillis(3000L);
    pool.setSoftMinEvictableIdleTimeMillis(1000L);
    pool.setMinIdle(2);

    Object[] active = new Object[5];
    Long[] creationTime = new Long[5];
    for (int i = 0; i < 5; i++) {
        active[i] = pool.borrowObject();
        creationTime[i] = new Long(((TimeTest) active[i]).getCreateTime());
    }

    for (int i = 0; i < 5; i++) {
        pool.returnObject(active[i]);
    }

    // Soft evict all but minIdle(2)
    Thread.sleep(1500L);
    pool.evict();
    assertEquals("Idle count different than expected.", 2, pool.getNumIdle());

    // Hard evict the rest.
    Thread.sleep(2000L);
    pool.evict();
    assertEquals("Idle count different than expected.", 0, pool.getNumIdle());
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

private void checkEvictorVisiting(boolean lifo) throws Exception {
    VisitTrackerFactory factory = new VisitTrackerFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(2);//  ww w .  j  ava 2s  .c o m
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // Visit oldest 2 - 0 and 1
    Object obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO will move 0 and 1 to end
    // LIFO, 7 out, then in, then out, then in
    pool.evict(); // Should visit 2 and 3 in either case
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() >= 4) {
            assertEquals("Unexpected instance visited " + tracker.getId(), 0, tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        }
    }

    factory = new VisitTrackerFactory();
    pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(3);
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // 0, 1, 2
    pool.evict(); // 3, 4, 5
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO 3,4,5,6,7,0,1,2
    // LIFO 7,6,5,4,3,2,1,0
    // In either case, pointer should be at 6
    pool.evict();
    // Should hit 6,7,0 - 0 for second time
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() != 0) {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 2,
                    tracker.getValidateCount());
        }
    }
    // Randomly generate a pools with random numTests
    // and make sure evictor cycles through elements appropriately
    int[] smallPrimes = { 2, 3, 5, 7 };
    Random random = new Random();
    random.setSeed(System.currentTimeMillis());
    for (int i = 0; i < 4; i++) {
        pool.setNumTestsPerEvictionRun(smallPrimes[i]);
        for (int j = 0; j < 5; j++) {
            pool = new GenericObjectPool(factory);
            pool.setNumTestsPerEvictionRun(3);
            pool.setMinEvictableIdleTimeMillis(-1);
            pool.setTestWhileIdle(true);
            pool.setLifo(lifo);
            pool.setTestOnReturn(false);
            pool.setTestOnBorrow(false);
            pool.setMaxIdle(-1);
            int instanceCount = 10 + random.nextInt(20);
            pool.setMaxActive(instanceCount);
            for (int k = 0; k < instanceCount; k++) {
                pool.addObject();
            }

            // Execute a random number of evictor runs
            int runs = 10 + random.nextInt(50);
            for (int k = 0; k < runs; k++) {
                pool.evict();
            }

            // Number of times evictor should have cycled through the pool
            int cycleCount = (runs * pool.getNumTestsPerEvictionRun()) / instanceCount;

            // Look at elements and make sure they are visited cycleCount
            // or cycleCount + 1 times
            VisitTracker tracker = null;
            int visitCount = 0;
            for (int k = 0; k < instanceCount; k++) {
                tracker = (VisitTracker) pool.borrowObject();
                assertTrue(pool.getNumActive() <= pool.getMaxActive());
                visitCount = tracker.getValidateCount();
                assertTrue(visitCount >= cycleCount && visitCount <= cycleCount + 1);
            }
        }
    }
}

From source file:org.apache.hadoop.hive.metastore.datasource.DbCPDataSourceProvider.java

@Override
public DataSource create(Configuration hdpConfig) throws SQLException {

    LOG.debug("Creating dbcp connection pool for the MetaStore");

    String driverUrl = DataSourceProvider.getMetastoreJdbcDriverUrl(hdpConfig);
    String user = DataSourceProvider.getMetastoreJdbcUser(hdpConfig);
    String passwd = DataSourceProvider.getMetastoreJdbcPasswd(hdpConfig);
    int maxPoolSize = hdpConfig.getInt(MetastoreConf.ConfVars.CONNECTION_POOLING_MAX_CONNECTIONS.getVarname(),
            ((Long) MetastoreConf.ConfVars.CONNECTION_POOLING_MAX_CONNECTIONS.getDefaultVal()).intValue());
    long connectionTimeout = hdpConfig.getLong(CONNECTION_TIMEOUT_PROPERTY, 30000L);
    int connectionMaxIlde = hdpConfig.getInt(CONNECTION_MAX_IDLE_PROPERTY, GenericObjectPool.DEFAULT_MAX_IDLE);
    int connectionMinIlde = hdpConfig.getInt(CONNECTION_MIN_IDLE_PROPERTY, GenericObjectPool.DEFAULT_MIN_IDLE);
    boolean testOnBorrow = hdpConfig.getBoolean(CONNECTION_TEST_BORROW_PROPERTY,
            GenericObjectPool.DEFAULT_TEST_ON_BORROW);
    long evictionTimeMillis = hdpConfig.getLong(CONNECTION_MIN_EVICT_MILLIS_PROPERTY,
            GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
    boolean testWhileIdle = hdpConfig.getBoolean(CONNECTION_TEST_IDLEPROPERTY,
            GenericObjectPool.DEFAULT_TEST_WHILE_IDLE);
    long timeBetweenEvictionRuns = hdpConfig.getLong(CONNECTION_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
    int numTestsPerEvictionRun = hdpConfig.getInt(CONNECTION_NUM_TESTS_PER_EVICTION_RUN,
            GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN);
    boolean testOnReturn = hdpConfig.getBoolean(CONNECTION_TEST_ON_RETURN,
            GenericObjectPool.DEFAULT_TEST_ON_RETURN);
    long softMinEvictableIdleTimeMillis = hdpConfig.getLong(CONNECTION_SOFT_MIN_EVICTABLE_IDLE_TIME,
            GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
    boolean lifo = hdpConfig.getBoolean(CONNECTION_LIFO, GenericObjectPool.DEFAULT_LIFO);

    GenericObjectPool objectPool = new GenericObjectPool();
    objectPool.setMaxActive(maxPoolSize);
    objectPool.setMaxWait(connectionTimeout);
    objectPool.setMaxIdle(connectionMaxIlde);
    objectPool.setMinIdle(connectionMinIlde);
    objectPool.setTestOnBorrow(testOnBorrow);
    objectPool.setTestWhileIdle(testWhileIdle);
    objectPool.setMinEvictableIdleTimeMillis(evictionTimeMillis);
    objectPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
    objectPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    objectPool.setTestOnReturn(testOnReturn);
    objectPool.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
    objectPool.setLifo(lifo);//w ww  . j a  v  a2 s. c  o  m

    ConnectionFactory connFactory = new DriverManagerConnectionFactory(driverUrl, user, passwd);
    // This doesn't get used, but it's still necessary, see
    // https://git1-us-west.apache.org/repos/asf?p=commons-dbcp.git;a=blob;f=doc/ManualPoolingDataSourceExample.java;
    // h=f45af2b8481f030b27364e505984c0eef4f35cdb;hb=refs/heads/DBCP_1_5_x_BRANCH
    new PoolableConnectionFactory(connFactory, objectPool, null, null, false, true);

    return new PoolingDataSource(objectPool);
}

From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java

protected ObjectPool createConnectionPool(GenericObjectPool.Config config, AbandonedConfig ac) {
    final GenericObjectPool connectionPool;
    final boolean doRemoveAbandoned = ac != null && ac.getRemoveAbandoned();

    if (doRemoveAbandoned) {
        connectionPool = new AbandonedObjectPool(null, ac);
    } else {//from  www  . j a v  a 2  s.c o  m
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(config.maxActive);
    connectionPool.setMaxIdle(config.maxIdle);
    connectionPool.setMinIdle(config.minIdle);
    connectionPool.setMaxWait(config.maxWait);
    connectionPool.setTestOnBorrow(config.testOnBorrow);
    connectionPool.setTestOnReturn(config.testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(config.timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(config.numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(config.minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(config.testWhileIdle);
    return connectionPool;
}

From source file:org.graylog2.syslog4j.impl.pool.generic.GenericSyslogPoolFactory.java

protected void configureGenericObjectPool(GenericObjectPool genericObjectPool) throws SyslogRuntimeException {
    SyslogPoolConfigIF poolConfig = null;

    try {//from  w w  w . j  a  va 2s.com
        poolConfig = (SyslogPoolConfigIF) this.syslog.getConfig();

    } catch (ClassCastException cce) {
        throw new SyslogRuntimeException("config must implement interface SyslogPoolConfigIF");
    }

    genericObjectPool.setMaxActive(poolConfig.getMaxActive());
    genericObjectPool.setMaxIdle(poolConfig.getMaxIdle());
    genericObjectPool.setMaxWait(poolConfig.getMaxWait());
    genericObjectPool.setMinEvictableIdleTimeMillis(poolConfig.getMinEvictableIdleTimeMillis());
    genericObjectPool.setMinIdle(poolConfig.getMinIdle());
    genericObjectPool.setNumTestsPerEvictionRun(poolConfig.getNumTestsPerEvictionRun());
    genericObjectPool.setSoftMinEvictableIdleTimeMillis(poolConfig.getSoftMinEvictableIdleTimeMillis());
    genericObjectPool.setTestOnBorrow(poolConfig.isTestOnBorrow());
    genericObjectPool.setTestOnReturn(poolConfig.isTestOnReturn());
    genericObjectPool.setTestWhileIdle(poolConfig.isTestWhileIdle());
    genericObjectPool.setTimeBetweenEvictionRunsMillis(poolConfig.getTimeBetweenEvictionRunsMillis());
    genericObjectPool.setWhenExhaustedAction(poolConfig.getWhenExhaustedAction());
}

From source file:org.idevlab.rjc.ds.PoolableDataSource.java

private synchronized GenericObjectPool createPool() {
    if (closed) {
        throw new RedisException("Data source is closed");
    }/*from  ww  w  .j a  va 2 s .  c  o  m*/

    if (connectionPool == null) {
        GenericObjectPool gop = new GenericObjectPool();
        gop.setMaxActive(maxActive);
        gop.setMaxIdle(maxIdle);
        gop.setMinIdle(minIdle);
        gop.setMaxWait(maxWait);
        gop.setTestOnBorrow(testOnBorrow);
        gop.setTestOnReturn(testOnReturn);
        gop.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        gop.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
        gop.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        gop.setTestWhileIdle(testWhileIdle);
        connectionPool = gop;
        createConnectionFactory();
        try {
            for (int i = 0; i < initialSize; i++) {
                connectionPool.addObject();
            }
        } catch (Exception e) {
            throw new RedisException("Error preloading the connection pool", e);
        }
    }

    return connectionPool;
}

From source file:org.jaffa.persistence.engines.jdbcengine.datasource.DbcpDataSourceConnectionFactory.java

private void createDbcpDataSource() throws SQLException {
    try {//  w  ww. j a  v  a  2  s  .c om
        synchronized (dataSourceLock) {
            if (c_dataSource == null) {
                // First we load the underlying JDBC driver.
                Class.forName(getDriverClass());

                // Next, we'll need a ObjectPool that serves as the actual pool of connections.
                // We'll use a GenericObjectPool instance
                GenericObjectPool connectionPool = new GenericObjectPool(null);
                if (getMaximumConnections() != null)
                    connectionPool.setMaxActive(getMaximumConnections());
                if (getMinimumConnections() != null)
                    connectionPool.setMaxIdle(getMinimumConnections());
                if (getMaxWait() != null)
                    connectionPool.setMaxWait(getMaxWait());
                if (getTestOnBorrow() != null)
                    connectionPool.setTestOnBorrow(getTestOnBorrow());
                if (getTestOnReturn() != null)
                    connectionPool.setTestOnReturn(getTestOnReturn());

                // Next, we'll create a ConnectionFactory that the pool will use to create Connections.
                // We'll use the DriverManagerConnectionFactory
                ConnectionFactory connectionFactory = null;
                if (m_driverProperties == null || m_driverProperties.isEmpty())
                    connectionFactory = new DriverManagerConnectionFactory(getUrl(), getUser(), getPassword());
                else
                    connectionFactory = new DriverManagerConnectionFactory(getUrl(), getDriverProperties());
                // Now we'll create the PoolableConnectionFactory, which wraps the "real" Connections created by the ConnectionFactory with the classes that implement the pooling functionality.
                KeyedObjectPoolFactory stmtPoolFactory = new StackKeyedObjectPoolFactory();
                String validationQuery = getValidationQuery();
                boolean defaultReadOnly = false;
                boolean defaultAutoCommit = false;
                PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                        connectionFactory, connectionPool, stmtPoolFactory, validationQuery, defaultReadOnly,
                        defaultAutoCommit);

                // Finally, we create the PoolingDriver itself, passing in the object pool we created.
                c_dataSource = new PoolingDataSource(connectionPool);

                // This will allow us to access the underlying Connection objects, required by the JdbcSecurityPlugin
                ((PoolingDataSource) c_dataSource).setAccessToUnderlyingConnectionAllowed(true);

                if (log.isDebugEnabled())
                    log.debug("Created the Dbcp DataSource");
            }
        }
    } catch (Exception e) {
        String str = "Error in creating the Dbcp DataSource";
        log.error(str, e);
        throw new SQLException(str);
    }
}

From source file:org.jvoicexml.implementation.pool.KeyedResourcePool.java

/**
 * Adds the given resource factory./*from   w ww  . j a  v  a 2  s  .  c  om*/
 * @param resourceFactory The {@link ResourceFactory} to add.
 * @exception Exception error populating the pool
 */
public void addResourceFactory(final ResourceFactory<T> resourceFactory) throws Exception {
    final PoolableObjectFactory factory = new PoolableResourceFactory<T>(resourceFactory);
    final GenericObjectPool pool = new GenericObjectPool(factory);
    final int instances = resourceFactory.getInstances();
    pool.setMinIdle(instances);
    pool.setMaxActive(instances);
    pool.setMaxIdle(instances);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);
    final String type = resourceFactory.getType();
    pools.put(type, pool);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("loading resources of type '" + type + "'...");
    }
    for (int i = 0; i < instances; i++) {
        pool.addObject();
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("...resources loaded.");
    }
}

From source file:org.kchine.rpf.db.ServantProxyPoolSingletonDB.java

public static GenericObjectPool getInstance(String poolName, String driver, final String url, final String user,
        final String password) {
    String key = driver + "%" + poolName + "%" + url + "%" + user + "%" + password;
    if (_pool.get(key) != null)
        return _pool.get(key);
    synchronized (lock) {
        if (_pool.get(key) == null) {
            Connection conn = null;
            try {
                Class.forName(driver);
                final Vector<Object> borrowedObjects = new Vector<Object>();
                DBLayerInterface dbLayer = DBLayer.getLayer(getDBType(url), new ConnectionProvider() {
                    public Connection newConnection() throws SQLException {
                        return DriverManager.getConnection(url, user, password);
                    }//from  w  w  w .  ja v a2  s.c  o  m
                });
                final GenericObjectPool p = new GenericObjectPool(
                        new ServantProxyFactoryDB(poolName, dbLayer)) {
                    @Override
                    public synchronized Object borrowObject() throws Exception {
                        if (_shuttingDown)
                            throw new NoSuchElementException();
                        Object result = super.borrowObject();
                        borrowedObjects.add(result);
                        return result;
                    }

                    @Override
                    public synchronized void returnObject(Object obj) throws Exception {
                        super.returnObject(obj);
                        borrowedObjects.remove(obj);
                    }
                };

                if (System.getProperty("pools.dbmode.shutdownhook.enabled") != null
                        && System.getProperty("pools.dbmode.shutdownhook.enabled").equalsIgnoreCase("false")) {

                } else {
                    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                        public void run() {
                            synchronized (p) {

                                final Vector<Object> bo = (Vector<Object>) borrowedObjects.clone();

                                _shuttingDown = true;
                                try {
                                    for (int i = 0; i < bo.size(); ++i)
                                        p.returnObject(bo.elementAt(i));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }));
                }

                _pool.put(key, p);
                p.setMaxIdle(0);
                p.setTestOnBorrow(true);
                p.setTestOnReturn(true);
            } catch (Exception e) {
                throw new RuntimeException(getStackTraceAsString(e));
            }

        }
        return _pool.get(key);
    }
}

From source file:org.kchine.rpf.db.ServantProxyPoolSingletonDB.java

public static GenericObjectPool getInstance(String poolName, DBLayerInterface dbLayer) {
    String key = poolName + "%" + dbLayer.toString();

    if (_pool.get(key) != null)
        return _pool.get(key);
    synchronized (lock) {
        if (_pool.get(key) == null) {
            Connection conn = null;
            try {
                final Vector<Object> borrowedObjects = new Vector<Object>();

                final GenericObjectPool p = new GenericObjectPool(
                        new ServantProxyFactoryDB(poolName, dbLayer)) {
                    @Override/*from w w  w  .  j av a 2 s .  com*/
                    public synchronized Object borrowObject() throws Exception {
                        if (_shuttingDown)
                            throw new NoSuchElementException();
                        Object result = super.borrowObject();
                        borrowedObjects.add(result);
                        return result;
                    }

                    @Override
                    public synchronized void returnObject(Object obj) throws Exception {
                        super.returnObject(obj);
                        borrowedObjects.remove(obj);
                    }
                };

                if (System.getProperty("pools.dbmode.shutdownhook.enabled") != null
                        && System.getProperty("pools.dbmode.shutdownhook.enabled").equalsIgnoreCase("false")) {

                } else {
                    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                        public void run() {
                            synchronized (p) {

                                final Vector<Object> bo = (Vector<Object>) borrowedObjects.clone();

                                _shuttingDown = true;
                                try {
                                    for (int i = 0; i < bo.size(); ++i)
                                        p.returnObject(bo.elementAt(i));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }));
                }

                _pool.put(key, p);
                p.setMaxIdle(0);
                p.setTestOnBorrow(true);
                p.setTestOnReturn(true);
            } catch (Exception e) {
                throw new RuntimeException(getStackTraceAsString(e));
            }

        }
        return _pool.get(key);
    }
}