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

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

Introduction

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

Prototype

public synchronized void setWhenExhaustedAction(byte whenExhaustedAction) 

Source Link

Document

Sets the action to take when the #borrowObject method is invoked when the pool is exhausted (the maximum number of "active" objects has been reached).

Usage

From source file:org.apache.hadoop.hive.metastore.MyXid.java

public synchronized static void checkGlobalPoolingDataSource(String url, String user, String pass) {
    if (globalDbConPool != null) {
        return;//from  w w  w  . j ava  2 s .c  om
    } else {
        LOG.error(
                "#################################################################### init master connetion pool");
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);
        GenericObjectPool connectionPool = new GenericObjectPool();
        connectionPool.setMaxActive(poolActiveSize);
        connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
        connectionPool.setMaxWait(10000);
        connectionPool.setTestOnBorrow(true);
        connectionPool.setTestWhileIdle(true);
        connectionPool.setTimeBetweenEvictionRunsMillis(30000);
        connectionPool.setMinEvictableIdleTimeMillis(300000);
        connectionPool.setLifo(true);

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);

        globalDbConPool = new PoolingDataSource(connectionPool);
        LOG.error(
                "#################################################################### init global connetion pool over");
    }
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

public synchronized static PoolingDataSource getSegPoolingDataSource(String url, String user, String pass) {
    url = url.toLowerCase();/* www.j ava2 s .co  m*/
    PoolingDataSource pool = SegmentDbConPool.get(url);
    if (pool != null) {
        return pool;
    } else {
        LOG.debug(
                "#################################################################### init global connetion pool:"
                        + url);
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, pass);
        GenericObjectPool connectionPool = new GenericObjectPool();
        connectionPool.setMaxActive(poolActiveSize);
        connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
        connectionPool.setMaxWait(10000);
        connectionPool.setTestOnBorrow(true);
        connectionPool.setTestWhileIdle(true);
        connectionPool.setTimeBetweenEvictionRunsMillis(30000);
        connectionPool.setMinEvictableIdleTimeMillis(300000);
        connectionPool.setLifo(true);

        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
                connectionPool, null, null, false, true);

        pool = new PoolingDataSource(connectionPool);
        SegmentDbConPool.put(url, pool);

        LOG.debug(
                "#################################################################### init global connetion pool:"
                        + url + " over");
        return pool;
    }
}

From source file:org.datacleaner.util.ws.PooledServiceSession.java

/**
 * Creates a connection pool that can be used for one or more
 * {@link PooledServiceSession} objects.
 * // www  .  j  a v a 2  s.  c o  m
 * @param maxConnections
 * @return
 */
public static GenericObjectPool<Integer> createConnectionPool(int maxConnections) {
    GenericObjectPool<Integer> connectionPool = new GenericObjectPool<Integer>(
            new ConnectionPoolObjectFactory());
    connectionPool.setMaxActive(maxConnections);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    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 av a  2 s.  c om*/
        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.hibernate.connection.DBCPConnectionProvider.java

public void configure(Properties props) throws HibernateException {
    try {//  www. j  a  va  2s  . c  om
        log.debug("Configure DBCPConnectionProvider");

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);
        String jdbcUrl = props.getProperty(Environment.URL);
        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        String password = props.getProperty(Environment.PASS);
        dbcpProperties.put("username", username);
        dbcpProperties.put("password", password);

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set)
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderFactory.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Object o : props.keySet()) {
            String key = String.valueOf(o);
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        // Let the factory create the pool
        ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(dbcpProperties);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = ds.getConnection();
        conn.close();

        // then we set the whenExhausted flag (the hard way...)
        Field poolField = BasicDataSource.class.getDeclaredField("connectionPool");
        poolField.setAccessible(true);
        GenericObjectPool connectionPool = (GenericObjectPool) poolField.get(ds);
        connectionPool.setWhenExhaustedAction((byte) 2);
    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        log.fatal(message, e);
        if (ds != null) {
            try {
                ds.close();
            } catch (Exception e2) {
                // ignore
            }
            ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");
}

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

/**
 * Adds the given resource factory.//from   w  ww  .  jav a  2s  .c  o  m
 * @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.mule.transport.ftp.FtpConnector.java

protected GenericObjectPool createPool(FtpConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }//  w  ww .  j a  v a 2s.c om
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

From source file:org.mule.transport.ftps.FtpsConnector.java

protected GenericObjectPool createPool(FtpsConnectionFactory connectionFactory) {
    GenericObjectPool genericPool = new GenericObjectPool(connectionFactory);
    byte poolExhaustedAction = ThreadingProfile.DEFAULT_POOL_EXHAUST_ACTION;

    ThreadingProfile receiverThreadingProfile = this.getReceiverThreadingProfile();
    if (receiverThreadingProfile != null) {
        int threadingProfilePoolExhaustedAction = receiverThreadingProfile.getPoolExhaustedAction();
        if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_WAIT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_ABORT) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if (threadingProfilePoolExhaustedAction == ThreadingProfile.WHEN_EXHAUSTED_RUN) {
            poolExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }//from w w w  .j a  v  a  2 s  .co  m
    }

    genericPool.setWhenExhaustedAction(poolExhaustedAction);
    genericPool.setTestOnBorrow(isValidateConnections());
    return genericPool;
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Initialize a jdbc connection pool//w w  w.  j  a v  a  2 s  .c om
 * 
 * @param type
 *            either rw or query pool
 * @param maxActive
 *            maximum number of connections in pool
 * @param configuration
 *            configuration properties used for creating database connections
 * @return connection pool
 * @throws AnzoException
 *             {@link ExceptionConstants#RDB.DRIVER_NAME} if there was a problem loading class for database driver
 */
private GenericObjectPool initializeConnectionFactory(boolean write, int maxActive) throws AnzoException {
    // Will use in jndi
    // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties));
    try {
        Class.forName(configuration.getDriverClassName());
    } catch (ClassNotFoundException e1) {
        throw new AnzoException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName());
    }
    Properties props = new Properties();
    props.put("user", configuration.getUser());
    props.put("password", configuration.getPassword());
    props.put("SetBigStringTryClob", "true");
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), props);
    GenericObjectPool connectionPool = new GenericObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(Math.max(1, maxActive / 2));
    connectionPool.setMinIdle(0);
    connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 10);
    connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 10);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.setMaxWait(GenericKeyedObjectPool.DEFAULT_MAX_WAIT);
    connectionPool.setTestOnBorrow(true);
    GenericKeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(null, PS_CACHE_SIZE,
            GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, GenericKeyedObjectPool.DEFAULT_MAX_WAIT, PS_CACHE_SIZE,
            PS_CACHE_SIZE, GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW,
            GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN,
            GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS,
            GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
            GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS,
            GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE);
    PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool,
            statementPool, configuration.getValidationQuery(), false, true) {
        @Override
        public synchronized Object makeObject() throws Exception {
            Connection connection = (Connection) super.makeObject();
            initializeConnection(connection);
            return connection;
        }
    };

    if (configuration.getSupportsIsolation() && write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    else if (configuration.getSupportsIsolation() && !write)
        pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    return connectionPool;
}

From source file:org.openanzo.jdbc.container.RDBQuadStorePool.java

private void setupPool(GenericObjectPool pool, RDBQuadStoreFactory factory, int maxActive, int maxIdle,
        long blockWait) {
    pool.setFactory(factory);/*from   ww w.  java  2s. c  om*/
    pool.setMaxActive(maxActive);
    pool.setMaxIdle(maxIdle);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(blockWait);
}