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:com.panet.imeta.core.database.ConnectionPoolUtil.java

private static void createPool(DatabaseMeta databaseMeta, String partitionId, int initialSize, int maximumSize)
        throws KettleDatabaseException {
    LogWriter.getInstance().logBasic(databaseMeta.toString(),
            Messages.getString("Database.CreatingConnectionPool", databaseMeta.getName()));
    GenericObjectPool gpool = new GenericObjectPool();

    gpool.setMaxIdle(-1);
    gpool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    gpool.setMaxActive(maximumSize);/*from   ww w. ja  v a 2 s  . com*/

    String clazz = databaseMeta.getDriverClass();
    try {
        Class.forName(clazz).newInstance();
    } catch (Exception e) {
        throw new KettleDatabaseException(Messages.getString(
                "Database.UnableToLoadConnectionPoolDriver.Exception", databaseMeta.getName(), clazz), e);
    }

    String url;
    String userName;
    String password;

    try {
        url = databaseMeta.environmentSubstitute(databaseMeta.getURL(partitionId));
        userName = databaseMeta.environmentSubstitute(databaseMeta.getUsername());
        password = databaseMeta.environmentSubstitute(databaseMeta.getPassword());
    } catch (RuntimeException e) {
        url = databaseMeta.getURL(partitionId);
        userName = databaseMeta.getUsername();
        password = databaseMeta.getPassword();
    }

    // Get the list of pool properties
    Properties originalProperties = databaseMeta.getConnectionPoolingProperties();
    //Add user/pass
    originalProperties.setProperty("user", Const.NVL(userName, ""));
    originalProperties.setProperty("password", Const.NVL(password, ""));

    // Now, replace the environment variables in there...
    Properties properties = new Properties();
    Iterator<Object> iterator = originalProperties.keySet().iterator();
    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String value = originalProperties.getProperty(key);
        properties.put(key, databaseMeta.environmentSubstitute(value));
    }

    // Create factory using these properties.
    //
    ConnectionFactory cf = new DriverManagerConnectionFactory(url, properties);

    new PoolableConnectionFactory(cf, gpool, null, null, false, false);

    for (int i = 0; i < initialSize; i++) {
        try {
            gpool.addObject();
        } catch (Exception e) {
            throw new KettleDatabaseException(
                    Messages.getString("Database.UnableToPreLoadConnectionToConnectionPool.Exception"), e);
        }
    }

    pd.registerPool(databaseMeta.getName(), gpool);

    LogWriter.getInstance().logBasic(databaseMeta.toString(),
            Messages.getString("Database.CreatedConnectionPool", databaseMeta.getName()));
}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java

/**
 * Creates a DataSource with connection pooling as provided by Apache DBCP
 *
 * @return a DataSource//from ww  w . ja  v  a  2  s. com
 */
public static DataSource configureAndCreateDataSource() {

    log.debug("Configuring DataSource wrapped in a Database Connection Pool, using custom loader");

    GlobalConfiguration globalConfiguration = GlobalConfigurationImpl.getInstance();

    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();

    log.debug("Loading JDBC Driver with custom class path: " + jdbcDriverClassPath);
    // Creates a new class loader, which will be used for loading our JDBC driver
    URLClassLoader urlClassLoader = getOxalisClassLoaderForJdbc(jdbcDriverClassPath);

    String className = globalConfiguration.getJdbcDriverClassName();
    String connectURI = globalConfiguration.getJdbcConnectionURI();
    String userName = globalConfiguration.getJdbcUsername();
    String password = globalConfiguration.getJdbcPassword();

    log.debug("className=" + className);
    log.debug("connectURI=" + connectURI);
    log.debug("userName=" + userName);
    log.debug("password=" + password);

    // Loads the JDBC Driver in a separate class loader
    Driver driver = getJdbcDriver(jdbcDriverClassPath, urlClassLoader, className);

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);

    // DBCP factory which will produce JDBC Driver instances
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectURI, properties);

    // DBCP object pool holding our driver connections
    GenericObjectPool genericObjectPool = new GenericObjectPool(null);
    genericObjectPool.setMaxActive(100);
    genericObjectPool.setMaxIdle(30);
    genericObjectPool.setMaxWait(10000);

    genericObjectPool.setTestOnBorrow(true); // Test the connection returned from the pool

    genericObjectPool.setTestWhileIdle(true); // Test idle instances visited by the pool maintenance thread and destroy any that fail validation
    genericObjectPool.setTimeBetweenEvictionRunsMillis(60 * 60 * 1000); // Test every hour

    // DBCP Factory holding the pooled connection, which are created by the driver connection factory and held in the supplied pool
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(driverConnectionFactory,
            genericObjectPool, null, null, false, true);

    String validationQuery = globalConfiguration.getValidationQuery();
    poolableConnectionFactory.setValidationQuery(validationQuery);

    // Creates the actual DataSource instance
    PoolingDataSource poolingDataSource = new PoolingDataSource(genericObjectPool);

    return poolingDataSource;

}

From source file:com.foxelbox.foxbukkit.database.DatabaseConnectionPool.java

private DatabaseConnectionPool() {
    try {/*from ww  w . j  av  a2  s  . c om*/
        Class.forName("com.mysql.jdbc.Driver");
    } catch (Exception e) {
        System.err.println("Error loading JBBC MySQL: " + e.toString());
    }

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    connectionPool.setMaxActive(10);
    connectionPool.setMaxIdle(5);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setTestOnReturn(true);
    connectionPool.setTestWhileIdle(true);

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            FoxBukkit.instance.configuration.getValue("database-uri",
                    "jdbc:mysql://localhost:3306/foxbukkit_database"),
            FoxBukkit.instance.configuration.getValue("database-user", "root"),
            FoxBukkit.instance.configuration.getValue("database-password", "password"));
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, new StackKeyedObjectPoolFactory(), "SELECT 1", false, true);
    poolableConnectionFactory.setValidationQueryTimeout(3);

    dataSource = new PoolingDataSource(connectionPool);

    try {
        initialize();
    } catch (SQLException exc) {
        System.err.println("Error initializing MySQL Database");
        exc.printStackTrace();
    }
}

From source file:lineage2.commons.dbcp.BasicDataSource.java

/**
 * Constructor for BasicDataSource./*w w  w .ja v a  2s . c o  m*/
 * @param driver String
 * @param connectURI String
 * @param uname String
 * @param passwd String
 * @param maxActive int
 * @param maxIdle int
 * @param idleTimeOut int
 * @param idleTestPeriod int
 * @param poolPreparedStatements boolean
 */
public BasicDataSource(String driver, String connectURI, String uname, String passwd, int maxActive,
        int maxIdle, int idleTimeOut, int idleTestPeriod, boolean poolPreparedStatements) {
    GenericObjectPool<?> connectionPool = new GenericObjectPool<>(null);
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(1);
    connectionPool.setMaxWait(-1L);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setTestOnBorrow(false);
    connectionPool.setTestWhileIdle(true);
    connectionPool.setTimeBetweenEvictionRunsMillis(idleTestPeriod * 1000L);
    connectionPool.setNumTestsPerEvictionRun(maxActive);
    connectionPool.setMinEvictableIdleTimeMillis(idleTimeOut * 1000L);
    GenericKeyedObjectPoolFactory<?, ?> statementPoolFactory = null;
    if (poolPreparedStatements) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory<>(null, -1,
                GenericObjectPool.WHEN_EXHAUSTED_FAIL, 0L, 1, GenericKeyedObjectPool.DEFAULT_MAX_TOTAL);
    }
    Properties connectionProperties = new Properties();
    connectionProperties.put("user", uname);
    connectionProperties.put("password", passwd);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, connectionProperties);
    @SuppressWarnings("unused")
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, statementPoolFactory, "SELECT 1", false, true);
    PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
    _connectionPool = connectionPool;
    _source = dataSource;
}

From source file:com.nesscomputing.syslog4j.impl.pool.generic.GenericSyslogPoolFactory.java

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

    try {/*  ww  w  .  j a v  a 2  s . 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:com.zotoh.core.db.JDBCPoolManager.java

private synchronized JDBCPool create(String pool, JDBCInfo param, Properties props) throws SQLException {
    if (existsPool(pool)) {
        throw new SQLException("Jdbc Pool already exists: " + pool);
    }//ww  w  .jav  a2  s. c  o  m

    PoolableConnectionFactory pcf;
    DriverConnectionFactory dcf;
    GenericObjectPool gop;
    DBVendor dbv;
    ObjectPool p;
    Driver d;

    tlog().debug("JDBCPoolMgr: Driver : {}", param.getDriver());
    tlog().debug("JDBCPoolMgr: URL : {}", param.getUrl());

    //        Ute.loadDriver(param.getDriver());
    d = DriverManager.getDriver(param.getUrl());
    dbv = DBUte.getDBVendor(param);

    dcf = new DriverConnectionFactory(d, param.getUrl(), props);
    gop = new GenericObjectPool();
    gop.setMaxActive(asInt(props.getProperty("max-conns"), 10));
    gop.setTestOnBorrow(true);
    gop.setMaxIdle(gop.getMaxActive());
    gop.setMinIdle(asInt(props.getProperty("min-conns"), 2));
    gop.setMaxWait(asLong(props.getProperty("max-wait4-conn-millis"), 1500L));
    gop.setMinEvictableIdleTimeMillis(asLong(props.getProperty("evict-conn-ifidle-millis"), 300000L));
    gop.setTimeBetweenEvictionRunsMillis(asLong(props.getProperty("check-evict-every-millis"), 60000L));

    pcf = new PoolableConnectionFactory(dcf, gop, null, null, true, false);
    pcf.setDefaultReadOnly(false);
    p = pcf.getPool();

    JDBCPool j = new JDBCPool(dbv, param, p);
    _ps.put(pool, j);

    tlog().debug("JDBCPoolMgr: Added db pool: {}, info= {}", pool, param);
    return j;
}

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

public void testSetFactoryWithNoActiveObjects() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    pool.setMaxIdle(10);
    pool.setFactory(new SimpleFactory());
    Object obj = pool.borrowObject();
    pool.returnObject(obj);// w w w .  j a v a 2  s  . com
    assertEquals(1, pool.getNumIdle());
    pool.setFactory(new SimpleFactory());
    assertEquals(0, pool.getNumIdle());
}

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

public void testSetFactoryWithActiveObjects() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    pool.setMaxIdle(10);
    pool.setFactory(new SimpleFactory());
    Object obj = pool.borrowObject();
    assertNotNull(obj);/*www  . ja va 2s .c  om*/
    try {
        pool.setFactory(null);
        fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
        // expected
    }
    try {
        pool.setFactory(new SimpleFactory());
        fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
        // expected
    }
}

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

protected ObjectPool makeEmptyPool(int mincap) {
    GenericObjectPool pool = new GenericObjectPool(new SimpleFactory());
    pool.setMaxActive(mincap);/* ww w.  j  a v  a  2s.  c  o m*/
    pool.setMaxIdle(mincap);
    return pool;
}

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

public void testSettersAndGetters() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    {/*from   w w  w . j a  v a  2 s. c o  m*/
        pool.setFactory(new SimpleFactory());
    }
    {
        pool.setMaxActive(123);
        assertEquals(123, pool.getMaxActive());
    }
    {
        pool.setMaxIdle(12);
        assertEquals(12, pool.getMaxIdle());
    }
    {
        pool.setMaxWait(1234L);
        assertEquals(1234L, pool.getMaxWait());
    }
    {
        pool.setMinEvictableIdleTimeMillis(12345L);
        assertEquals(12345L, pool.getMinEvictableIdleTimeMillis());
    }
    {
        pool.setNumTestsPerEvictionRun(11);
        assertEquals(11, pool.getNumTestsPerEvictionRun());
    }
    {
        pool.setTestOnBorrow(true);
        assertTrue(pool.getTestOnBorrow());
        pool.setTestOnBorrow(false);
        assertTrue(!pool.getTestOnBorrow());
    }
    {
        pool.setTestOnReturn(true);
        assertTrue(pool.getTestOnReturn());
        pool.setTestOnReturn(false);
        assertTrue(!pool.getTestOnReturn());
    }
    {
        pool.setTestWhileIdle(true);
        assertTrue(pool.getTestWhileIdle());
        pool.setTestWhileIdle(false);
        assertTrue(!pool.getTestWhileIdle());
    }
    {
        pool.setTimeBetweenEvictionRunsMillis(11235L);
        assertEquals(11235L, pool.getTimeBetweenEvictionRunsMillis());
    }
    {
        pool.setSoftMinEvictableIdleTimeMillis(12135L);
        assertEquals(12135L, pool.getSoftMinEvictableIdleTimeMillis());
    }
    {
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_FAIL, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_GROW, pool.getWhenExhaustedAction());
    }
}