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

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

Introduction

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

Prototype

byte WHEN_EXHAUSTED_BLOCK

To view the source code for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK.

Click Source Link

Document

A "when exhausted action" type indicating that when the pool is exhausted (i.e., the maximum number of active objects has been reached), the #borrowObject method should block until a new object is available, or the #getMaxWait maximum wait time has been reached.

Usage

From source file:org.pentaho.reporting.engine.classic.extensions.modules.connections.PooledDatasourceHelper.java

public static PoolingDataSource setupPooledDataSource(final IDatabaseConnection databaseConnection)
        throws DatasourceServiceException {
    try {/*w  w  w  . j  av a  2 s.com*/
        final DataSourceCacheManager cacheManager = ClassicEngineBoot.getInstance().getObjectFactory()
                .get(DataSourceCacheManager.class);
        final IDatabaseDialectService databaseDialectService = ClassicEngineBoot.getInstance()
                .getObjectFactory().get(IDatabaseDialectService.class);
        final IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection);

        final String driverClass;
        if (GENERIC.equals(databaseConnection.getDatabaseType().getShortName())) { //$NON-NLS-1$
            driverClass = databaseConnection.getAttributes()
                    .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS);
        } else {
            driverClass = dialect.getNativeDriver();
        }

        String url;
        try {
            url = dialect.getURLWithExtraOptions(databaseConnection);
        } catch (DatabaseDialectException e) {
            url = null;
        }

        // Read default connection pooling parameter
        final String maxdleConn = getSystemSetting("dbcp-defaults.max-idle-conn"); //$NON-NLS-1$
        final String minIdleConn = getSystemSetting("dbcp-defaults.min-idle-conn"); //$NON-NLS-1$
        final String maxActConn = getSystemSetting("dbcp-defaults.max-act-conn"); //$NON-NLS-1$
        String validQuery = null;
        final String whenExhaustedAction = getSystemSetting("dbcp-defaults.when-exhausted-action"); //$NON-NLS-1$
        final String wait = getSystemSetting("dbcp-defaults.wait"); //$NON-NLS-1$
        final String testWhileIdleValue = getSystemSetting("dbcp-defaults.test-while-idle"); //$NON-NLS-1$
        final String testOnBorrowValue = getSystemSetting("dbcp-defaults.test-on-borrow"); //$NON-NLS-1$
        final String testOnReturnValue = getSystemSetting("dbcp-defaults.test-on-return"); //$NON-NLS-1$
        final boolean testWhileIdle = !StringUtils.isEmpty(testWhileIdleValue)
                && Boolean.parseBoolean(testWhileIdleValue);
        final boolean testOnBorrow = !StringUtils.isEmpty(testOnBorrowValue)
                && Boolean.parseBoolean(testOnBorrowValue);
        final boolean testOnReturn = !StringUtils.isEmpty(testOnReturnValue)
                && Boolean.parseBoolean(testOnReturnValue);
        int maxActiveConnection = -1;
        long waitTime = -1;
        byte whenExhaustedActionType = -1;
        final int minIdleConnection = !StringUtils.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1;
        final int maxIdleConnection = !StringUtils.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1;

        final Map<String, String> attributes = databaseConnection.getAttributes();

        if (attributes.containsKey(DataBaseConnectionAttributes.MAX_ACTIVE_KEY)) {
            maxActiveConnection = Integer.parseInt(attributes.get(DataBaseConnectionAttributes.MAX_ACTIVE_KEY));
        } else {
            if (!StringUtils.isEmpty(maxActConn)) {
                maxActiveConnection = Integer.parseInt(maxActConn);
            }
        }
        if (attributes.containsKey(DataBaseConnectionAttributes.MAX_WAIT_KEY)) {
            waitTime = Integer.parseInt(attributes.get(DataBaseConnectionAttributes.MAX_WAIT_KEY));
        } else {
            if (!StringUtils.isEmpty(wait)) {
                waitTime = Long.parseLong(wait);
            }
        }
        if (attributes.containsKey(DataBaseConnectionAttributes.QUERY_KEY)) {
            validQuery = attributes.get(DataBaseConnectionAttributes.QUERY_KEY);
        }
        if (!StringUtils.isEmpty(whenExhaustedAction)) {
            whenExhaustedActionType = Byte.parseByte(whenExhaustedAction);
        } else {
            whenExhaustedActionType = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        }

        final PoolingDataSource poolingDataSource = new PoolingDataSource();

        // As the name says, this is a generic pool; it returns basic Object-class objects.
        final GenericObjectPool pool = new GenericObjectPool(null);
        pool.setWhenExhaustedAction(whenExhaustedActionType);

        // Tuning the connection pool
        pool.setMaxActive(maxActiveConnection);
        pool.setMaxIdle(maxIdleConnection);
        pool.setMaxWait(waitTime);
        pool.setMinIdle(minIdleConnection);
        pool.setTestWhileIdle(testWhileIdle);
        pool.setTestOnReturn(testOnReturn);
        pool.setTestOnBorrow(testOnBorrow);
        pool.setTestWhileIdle(testWhileIdle);
        /*
         * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory
         * because that essentially uses DriverManager as the source of connections.
         */
        final Properties properties = new Properties();
        properties.setProperty("user", databaseConnection.getUsername());
        properties.setProperty("password", databaseConnection.getPassword());
        final ConnectionFactory factory = new DriverConnectionFactory(getDriver(dialect, driverClass, url), url,
                properties);

        /*
         * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not
         * "Poolable[ConnectionFactory]."
         */
        // This declaration is used implicitly.
        // noinspection UnusedDeclaration
        final PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory
                pool, // ObjectPool
                null, // KeyedObjectPoolFactory
                validQuery, // String (validation query)
                false, // boolean (default to read-only?)
                true // boolean (default to auto-commit statements?)
        );

        /*
         * initialize the pool to X connections
         */
        logger.debug("Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle"
                + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
                + " idle connections."); //$NON-NLS-1$

        for (int i = 0; i < maxIdleConnection; ++i) {
            pool.addObject();
        }
        logger.debug(
                "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        /*
         * All of this is wrapped in a DataSource, which client code should already know how to handle (since it's the
         * same class of object they'd fetch via the container's JNDI tree
         */
        poolingDataSource.setPool(pool);

        // store the pool, so we can get to it later
        cacheManager.getDataSourceCache().put(databaseConnection.getName(), poolingDataSource);
        return (poolingDataSource);
    } catch (Exception e) {
        throw new DatasourceServiceException(e);
    }
}

From source file:org.quickserver.net.server.impl.BasicPoolManager.java

public ObjectPool makeByteBufferPool(PoolableObjectFactory factory, PoolConfig opConfig) {
    GenericObjectPool.Config bconfig = configurePool(opConfig);
    bconfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    return new GenericObjectPool(factory, bconfig);
}

From source file:org.rapidcontext.core.type.Connection.java

/**
 * Initializes this connection after loading it from a storage.
 * Any object initialization that may fail or that causes the
 * object to interact with any other part of the system (or
 * external systems) should be implemented here.
 *
 * @throws StorageException if the initialization failed
 *//*from w w w. j  ava  2  s  .c  o m*/
protected void init() throws StorageException {
    int open = maxOpen();
    int idle = maxIdleSeconds();

    dict.setInt("_" + KEY_MAX_OPEN, open);
    dict.setInt("_" + KEY_MAX_IDLE_SECS, idle);
    channelPool = new GenericObjectPool(new ChannelFactory());
    channelPool.setMaxActive(open);
    channelPool.setMaxIdle(open);
    channelPool.setMinIdle(0);
    channelPool.setMaxWait(MAX_ACQUIRE_WAIT);
    channelPool.setMinEvictableIdleTimeMillis(idle * 1000L);
    channelPool.setLifo(false);
    channelPool.setTestOnBorrow(true);
    channelPool.setTestOnReturn(true);
    channelPool.setTestWhileIdle(true);
    channelPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
}

From source file:org.sakaiproject.kernel.ldap.GenericObjectPoolTest.java

@Before
public void setUp() throws Exception {

    factory = createMock(PoolableObjectFactory.class);

    pool = new GenericObjectPool(factory, 1, // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            60000, // maxWait (millis)
            1, // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );// w ww.j  av  a2s .c  o m
}

From source file:org.sakaiproject.kernel.ldap.PoolingLdapConnectionManager.java

/**
 * {@inheritDoc}//from   w  ww. j a v  a  2 s . c o  m
 */
@Override
public void init() throws LdapException {
    super.init();

    if (pool != null) {
        return;
    }

    if (factory == null) {
        factory = new PooledLDAPConnectionFactory();
    }
    factory.setConnectionManager(this);

    pool = new GenericObjectPool(factory, getConfig().getPoolMaxConns(), // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            POOL_MAX_WAIT, // maxWait (millis)
            getConfig().getPoolMaxConns(), // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );
}

From source file:org.sakaiproject.nakamura.ldap.PoolingLdapConnectionManager.java

@Override
public void init(LdapConnectionManagerConfig config) {
    super.init(config);

    if (pool != null) {
        try {/*from   w ww .  ja  v  a 2s . co  m*/
            pool.close();
        } catch (Exception e) {
            // ignore
        }
        pool = null;
    }

    factory = newPooledLDAPConnectionFactory(this, livenessValidators);

    pool = newConnectionPool(factory, getConfig().getPoolMaxConns(), // maxActive
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // whenExhaustedAction
            POOL_MAX_WAIT, // maxWait (millis)
            getConfig().getPoolMaxConns(), // maxIdle
            true, // testOnBorrow
            false // testOnReturn
    );
}

From source file:org.sakaiproject.nakamura.lite.storage.AbstractClientConnectionPool.java

@Activate
public void activate(Map<String, Object> properties) throws ClassNotFoundException {
    // for testing purposes
    if (configuration == null) {
        configuration = (Configuration) properties.get(Configuration.class.getName());
    }/*  w  ww. j a  v a 2s. c om*/
    indexColums = ImmutableSet.of(configuration.getIndexColumnNames());
    int maxActive = StorageClientUtils.getSetting(properties.get(MAX_ACTIVE), 200);
    byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
    String whenExhausted = (String) properties.get(WHEN_EHAUSTED);
    if ("fail".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    } else if ("grow".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    } else if ("block".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    }
    long maxWait = StorageClientUtils.getSetting(properties.get(MAX_WAIT), 10L);
    int maxIdle = StorageClientUtils.getSetting(properties.get(MAX_IDLE), 5);
    boolean testOnBorrow = StorageClientUtils.getSetting(properties.get(TEST_ON_BORROW), true);
    boolean testOnReturn = StorageClientUtils.getSetting(properties.get(TEST_ON_RETURN), true);
    long timeBetweenEvictionRunsMillis = StorageClientUtils
            .getSetting(properties.get(TIME_BETWEEN_EVICTION_RUNS_MILLIS), 60000L);
    int numTestsPerEvictionRun = StorageClientUtils.getSetting(properties.get(NUM_TESTS_PER_EVICTION_RUN),
            1000);
    long minEvictableIdleTimeMillis = StorageClientUtils
            .getSetting(properties.get(MIN_EVICTABLE_IDLE_TIME_MILLIS), 10000L);
    boolean testWhileIdle = StorageClientUtils.getSetting(properties.get(TEST_WHILE_IDLE), false);

    pool = new GenericObjectPool(getConnectionPoolFactory(), maxActive, whenExhaustedAction, maxWait, maxIdle,
            testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
            minEvictableIdleTimeMillis, testWhileIdle);

    // set the maximum size of a string, if this is not 0, strings over this size will become files.
    StringType.setLengthLimit(StorageClientUtils.getSetting(properties.get(LONG_STRING_SIZE), 0));

}

From source file:org.sakaiproject.nakamura.lite.storage.spi.AbstractClientConnectionPool.java

@Activate
public void activate(Map<String, Object> properties) throws ClassNotFoundException {
    // for testing purposes
    if (configuration == null) {
        configuration = (Configuration) properties.get(Configuration.class.getName());
    }//from   ww  w  .j a va  2s .  c om
    indexColumns = ImmutableSet.copyOf(configuration.getIndexColumnNames());
    indexColumnsTypes = ImmutableSet.copyOf(configuration.getIndexColumnTypes());
    int maxActive = StorageClientUtils.getSetting(properties.get(MAX_ACTIVE), 200);
    byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
    String whenExhausted = (String) properties.get(WHEN_EHAUSTED);
    if ("fail".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
    } else if ("grow".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    } else if ("block".equals(whenExhausted)) {
        whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    }
    long maxWait = StorageClientUtils.getSetting(properties.get(MAX_WAIT), 10L);
    int maxIdle = StorageClientUtils.getSetting(properties.get(MAX_IDLE), 5);
    boolean testOnBorrow = StorageClientUtils.getSetting(properties.get(TEST_ON_BORROW), true);
    boolean testOnReturn = StorageClientUtils.getSetting(properties.get(TEST_ON_RETURN), true);
    long timeBetweenEvictionRunsMillis = StorageClientUtils
            .getSetting(properties.get(TIME_BETWEEN_EVICTION_RUNS_MILLIS), 60000L);
    int numTestsPerEvictionRun = StorageClientUtils.getSetting(properties.get(NUM_TESTS_PER_EVICTION_RUN),
            1000);
    long minEvictableIdleTimeMillis = StorageClientUtils
            .getSetting(properties.get(MIN_EVICTABLE_IDLE_TIME_MILLIS), 10000L);
    boolean testWhileIdle = StorageClientUtils.getSetting(properties.get(TEST_WHILE_IDLE), false);

    pool = new GenericObjectPool(getConnectionPoolFactory(), maxActive, whenExhaustedAction, maxWait, maxIdle,
            testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
            minEvictableIdleTimeMillis, testWhileIdle);

    // set the maximum size of a string, if this is not 0, strings over this size will become files.
    StringType.setLengthLimit(
            StorageClientUtils.getSetting(properties.get(LONG_STRING_SIZE), DEFAULT_LONG_STRING_SIZE));
    // location of the long string store.
    LongString.setBase(StorageClientUtils.getSetting(properties.get(LONG_STRING_STORE_BASE),
            StorageClientUtils.getSetting(properties.get(FS_STORE_BASE_DIR), DEFAULT_FILE_STORE)));

}

From source file:org.springframework.aop.target.CommonsPoolTargetSourceTests.java

@Test
public void testSetWhenExhaustedAction() {
    CommonsPoolTargetSource targetSource = new CommonsPoolTargetSource();
    targetSource.setWhenExhaustedActionName("WHEN_EXHAUSTED_BLOCK");
    assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, targetSource.getWhenExhaustedAction());
}

From source file:org.topazproject.ambra.auth.db.DatabaseContext.java

/**
 * Construct a db context//from   w  w  w .j  ava  2  s.  c om
 * @param jdbcDriver jdbcDriver
 * @param dbProperties dbProperties including url, user, password
 * @param initialSize initialSize of the pool
 * @param maxActive maxActive number of connections, after which it will block until a connection is
 *                  released
 * @param validationQuery to validate that the connection is still valid
 * @throws DatabaseException DatabaseException
 */
private DatabaseContext(final String jdbcDriver, final Properties dbProperties, final int initialSize,
        final int maxActive, final String validationQuery) throws DatabaseException {
    try {
        Class.forName(jdbcDriver);
    } catch (final ClassNotFoundException e) {
        throw new DatabaseException("Unable to load the db driver:" + jdbcDriver, e);
    }

    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
            dbProperties.getProperty("url"), dbProperties.getProperty("user"),
            dbProperties.getProperty("password"));

    connectionPool = new GenericObjectPool();
    connectionPool.setTestOnReturn(true);
    connectionPool.setMaxActive(maxActive);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    connectionPool.getMaxActive();

    final KeyedObjectPoolFactory stmtPool = new GenericKeyedObjectPoolFactory(null);

    /*
     * During instantiation, the PoolableConnectionFactory class registers itself to the
     * GenericObjectPool instance passed in its constructor. This factory class is used to create
     * new instances of the JDBC connections.
     */
    new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPool, validationQuery, false, true);

    for (int i = 0; i < initialSize; i++) {
        try {
            connectionPool.addObject();
        } catch (final Exception e) {
            throw new DatabaseException("Error initlaizing initial number of connections", e);
        }
    }
    dataSource = new PoolingDataSource(connectionPool);
}