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:com.adaptris.jdbc.connection.FailoverDatasourceTest.java

@Test(expected = SQLException.class)
public void testBorrow() throws Exception {
    GenericObjectPool objPool = new GenericObjectPool(new UselessLifeguard(config(), true, false),
            maxPoolSize(), GenericObjectPool.WHEN_EXHAUSTED_BLOCK, timeToWait());
    objPool.setTestOnBorrow(true);//from ww  w  .j av a2 s. c o  m
    objPool.setTestWhileIdle(true);
    overrideObjectPool(objPool);
    getConnection();
}

From source file:com.adaptris.jdbc.connection.FailoverDataSource.java

private void init(Properties p) {
    if (p == null) {
        throw new RuntimeException("No Configuration available ");
    }//from   www. j  a  va  2 s. c  om
    for (int i = 0; i < REQUIRED_PROPERTIES.length; i++) {
        if (!p.containsKey(REQUIRED_PROPERTIES[i])) {
            throw new RuntimeException("Missing Configuration " + REQUIRED_PROPERTIES[i]);
        }
    }
    databaseConfig = new FailoverConfig(p);
    poolMaximum = Integer.parseInt(p.getProperty(POOL_MAX_SIZE, "10"));
    poolTimeToWait = Integer.parseInt(p.getProperty(POOL_TIME_TO_WAIT, "20000"));
    pool = new GenericObjectPool(new PoolAttendant(databaseConfig), poolMaximum,
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, poolTimeToWait);
    pool.setTestOnBorrow(true);
    pool.setTestWhileIdle(true);
}

From source file:net.ontopia.persistence.proxy.DBCPConnectionFactory.java

protected void initPool() {
    // Set up connection pool
    pool = new GenericObjectPool(null);

    // Read/Write by default
    boolean readonly = defaultReadOnly;
    // Auto-commit disabled by default
    boolean autocommit = readonly;
    log.debug("Creating new DBCP connection factory, readonly=" + readonly + ", autocommit=" + autocommit);

    // Set minimum pool size (default: 20)
    String _minsize = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MinimumSize", false);
    int minsize = (_minsize == null ? 20 : Integer.parseInt(_minsize));
    log.debug("Setting ConnectionPool.MinimumSize '" + minsize + "'");
    pool.setMaxIdle(minsize); // 0 = no limit

    // Set maximum pool size (default: Integer.MAX_VALUE)
    String _maxsize = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.MaximumSize", false);
    int maxsize = (_maxsize == null ? 0 : Integer.parseInt(_maxsize));
    log.debug("Setting ConnectionPool.MaximumSize '" + maxsize + "'");
    pool.setMaxActive(maxsize); // 0 = no limit

    // Set user timeout (default: never)
    String _utimeout = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.UserTimeout", false);
    int utimeout = (_utimeout == null ? -1 : Integer.parseInt(_utimeout));
    pool.setMaxWait(utimeout); // -1 = never

    // Set soft maximum - emergency objects (default: true)
    boolean softmax = PropertyUtils.isTrue(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.SoftMaximum", true);
    log.debug("Setting ConnectionPool.SoftMaximum '" + softmax + "'");
    if (softmax)//from   www  .  j a v  a 2  s .com
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    else
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

    // allow the user to overwrite exhausted options
    // warning: when set to fail, make sure Maximum and Minimum are set correctly
    // warning: when set to block, make sure a propper usertimeout is set, or pool will block
    //          forever
    String _whenExhaustedAction = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.WhenExhaustedAction", false);
    if (EXHAUSED_BLOCK.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
    if (EXHAUSED_GROW.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
    if (EXHAUSED_FAIL.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);

    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK)
        log.debug("Pool is set to block on exhaused");
    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW)
        log.debug("Pool is set to grow on exhaused");
    if (pool.getWhenExhaustedAction() == GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL)
        log.debug("Pool is set to fail on exhaused");

    // Statement pool
    GenericKeyedObjectPoolFactory stmpool = null;
    if (PropertyUtils.isTrue(properties, "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.PoolStatements",
            true)) {
        log.debug("Using prepared statement pool: Yes");
        stmpool = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key) 
                GenericKeyedObjectPool.DEFAULT_MAX_TOTAL);
    } else {
        log.debug("Using prepared statement pool: No");
    }

    // Test on borrow
    pool.setTestOnBorrow(true);

    // Get validation query
    String vquery = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.ConnectionPool.ValidationQuery", false);
    if (vquery == null)
        vquery = "select seq_count from TM_ADMIN_SEQUENCE where seq_name = '<GLOBAL>'";

    try {
        // Make sure driver is registered
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Class.forName(getDriver(), true, classLoader);
        // Create connection factory
        ConnectionFactory cfactory;
        if (getUserName() == null || getPassword() == null) {
            Properties props = new Properties();
            props.putAll(properties);
            cfactory = new DriverManagerConnectionFactory(getConnectionString(), props);
        } else {
            cfactory = new DriverManagerConnectionFactory(getConnectionString(), getUserName(), getPassword());
        }

        // Create data source
        this.pcfactory = new TraceablePoolableConnectionFactory(cfactory, pool, stmpool, vquery, readonly,
                autocommit);

        // Set default transaction isolation level
        pcfactory.setDefaultTransactionIsolation(defaultTransactionIsolation);

        this.datasource = new PoolingDataSource(pool);
    } catch (Exception e) {
        throw new OntopiaRuntimeException("Problems occurred when setting up DBCP connection pool.", e);
    }
}

From source file:net.ontopia.topicmaps.impl.rdbms.RDBMSTopicMapReference.java

protected void init() {
    // store factory
    TopicMapStoreFactoryIF sfactory = new TopicMapStoreFactoryIF() {
        public TopicMapStoreIF createStore() {
            return _createStore(false);
        }/*from w w  w  .  jav  a  2  s  . co  m*/
    };

    // initialize pool
    this.ofactory = new StorePoolableObjectFactory(sfactory);
    this.pool = new GenericObjectPool(ofactory);
    this.pool.setTestOnBorrow(true);

    Map properties = storage.getProperties();
    if (properties != null) {
        // Set minimum pool size (default: 0)
        String _minsize = PropertyUtils.getProperty(properties,
                "net.ontopia.topicmaps.impl.rdbms.StorePool.MinimumSize", false);
        int minsize = (_minsize == null ? 0 : Integer.parseInt(_minsize));
        log.debug("Setting StorePool.MinimumSize '" + minsize + "'");
        pool.setMinIdle(minsize); // 0 = no limit

        // Set maximum pool size (default: Integer.MAX_VALUE)
        String _maxsize = PropertyUtils.getProperty(properties,
                "net.ontopia.topicmaps.impl.rdbms.StorePool.MaximumSize", false);
        int maxsize = (_maxsize == null ? 8 : Integer.parseInt(_maxsize));
        log.debug("Setting StorePool.MaximumSize '" + maxsize + "'");
        pool.setMaxActive(maxsize); // 0 = no limit

        // Set soft maximum - emergency objects (default: false)
        boolean softmax = PropertyUtils.isTrue(properties,
                "net.ontopia.topicmaps.impl.rdbms.StorePool.SoftMaximum", false);
        log.debug("Setting StorePool.SoftMaximum '" + softmax + "'");
        if (softmax)
            pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
        else
            pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    }

    // allow the user to fully overwrite exhausted options
    String _whenExhaustedAction = PropertyUtils.getProperty(properties,
            "net.ontopia.topicmaps.impl.rdbms.StorePool.WhenExhaustedAction", false);
    if (EXHAUSED_BLOCK.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    if (EXHAUSED_GROW.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    if (EXHAUSED_FAIL.equals(_whenExhaustedAction))
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);

    if (pool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_BLOCK)
        log.debug("Pool is set to block on exhaused");
    if (pool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_GROW)
        log.debug("Pool is set to grow on exhaused");
    if (pool.getWhenExhaustedAction() == GenericObjectPool.WHEN_EXHAUSTED_FAIL)
        log.debug("Pool is set to fail on exhaused");

}

From source file:com.sampas.socbs.core.data.arcsde.impl.ArcSDEConnectionPool.java

/**
 * Creates a new SdeConnectionPool object with the connection parameters
 * holded by <code>config</code>
 * /*ww  w . ja  v  a  2  s. co m*/
 * @param config
 *            holds connection options such as server, user and password, as
 *            well as tuning options as maximun number of connections
 *            allowed
 * 
 * @throws DataSourceException
 *             DOCUMENT ME!
 * @throws NullPointerException
 *             DOCUMENT ME!
 */
protected ArcSDEConnectionPool(ArcSDEConnectionConfig config) throws DataSourceException {
    if (config == null) {
        throw new NullPointerException("parameter config can't be null");
    }

    this.config = config;
    LOGGER.fine("populating ArcSDE connection pool");

    this.seConnectionFactory = new SeConnectionFactory(this.config);

    int minConnections = config.getMinConnections().intValue();
    int maxConnections = config.getMaxConnections().intValue();
    // byte exhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    byte exhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    long maxWait = config.getConnTimeOut().longValue();

    this.pool = new GenericObjectPool(seConnectionFactory, maxConnections, exhaustedAction, maxWait, true,
            true);
    LOGGER.info("Created ArcSDE connection pool for " + config);

    ArcSDEPooledConnection[] preload = new ArcSDEPooledConnection[minConnections];

    try {
        for (int i = 0; i < minConnections; i++) {
            preload[i] = (ArcSDEPooledConnection) this.pool.borrowObject();
            if (i == 0) {
                SeRelease seRelease = preload[i].getRelease();
                String sdeDesc = seRelease.getDesc();
                int major = seRelease.getMajor();
                int minor = seRelease.getMinor();
                int bugFix = seRelease.getBugFix();
                String desc = "ArcSDE " + major + "." + minor + "." + bugFix + " " + sdeDesc;
                LOGGER.info("Connected to " + desc);
            }
        }

        for (int i = 0; i < minConnections; i++) {
            this.pool.returnObject(preload[i]);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "can't connect to " + config, e);
        throw new DataSourceException(e);
    }
}

From source file:Pool162.java

public void testWhenExhaustedBlockInterupt() throws Exception {
    GenericObjectPool pool = new GenericObjectPool(new SimpleFactory());
    //Set this value to 1 to get the deadlock. No deadlock when it sets to 
    //other values.
    pool.setMaxActive(2);//from w  w  w .  jav a  2 s.  c  o m
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

    Object obj1 = pool.borrowObject();

    // Make sure one object was obtained
    if (obj1 == null) {
        throw new Exception("obj1 is null");
    }

    // Create a separate thread to try and borrow another object
    WaitingTestThread wtt = new WaitingTestThread(pool, 200);
    wtt.start();
    // Give wtt time to start
    Thread.sleep(200);
    //bug trigger #1
    wtt.interrupt();
    //bug trigger #1
    // Give interrupt time to take effect
    Thread.sleep(200);
    // Return object to the pool
    pool.returnObject(obj1);
    Object obj2 = null;
    obj2 = pool.borrowObject();
    if (obj2 == null) {
        throw new Exception("obj2 is null");
    }
    pool.returnObject(obj2);
    pool.close();
}

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

@Test
// @Schedule(name = "whenExhaustedBlockInterupt", value = "[beforeBorrow:afterBorrow]@borrowThread->beforeInterrupt@main,"+
//     "afterThrow@borrowThread->beforeCheck@main") 
public void testWhenExhaustedBlockInterrupt() throws Exception {
    this.setUp();
    pool.setMaxActive(1);/*from   w  w  w .  j a v  a2 s. c  o m*/
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(0);
    Object obj1 = pool.borrowObject();

    // Make sure on object was obtained
    assertNotNull(obj1);

    // Create a separate thread to try and borrow another object
    WaitingTestThread wtt = new WaitingTestThread(pool, 200);
    wtt.setName("borrowThread");
    wtt.start();
    // Give wtt time to start
    Thread.sleep(200);
    wtt.interrupt();

    // Give interupt time to take effect
    Thread.sleep(200);

    // Check thread was interrupted
    assertTrue(wtt._thrown instanceof InterruptedException);

    // Return object to the pool
    pool.returnObject(obj1);

    // Bug POOL-162 - check there is now an object in the pool
    pool.setMaxWait(10L);
    Object obj2 = null;
    try {
        obj2 = pool.borrowObject();
        assertNotNull(obj2);
    } catch (NoSuchElementException e) {
        // Not expected
        fail("NoSuchElementException not expected");
    }
    pool.returnObject(obj2);
    pool.close();
    this.tearDown();
}

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

@Test
@Schedule(name = "whenExhaustedBlockInterupt", value = "[beforeBorrow:afterBorrow]@borrowThread->beforeInterrupt@main,"
        + "afterThrow@borrowThread->beforeCheck@main")
public void testWhenExhaustedBlockInterupt() throws Exception {
    this.setUp();
    pool.setMaxActive(1);/*from  w w w  .  j  ava2 s  .  co  m*/
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(0);
    Object obj1 = pool.borrowObject();

    // Make sure on object was obtained
    assertNotNull(obj1);

    // Create a separate thread to try and borrow another object
    WaitingTestThread wtt = new WaitingTestThread(pool, 200);
    wtt.setName("borrowThread");
    wtt.start();
    // Give wtt time to start
    //Thread.sleep(200);
    fireEvent("beforeInterrupt");
    wtt.interrupt();

    // Give interupt time to take effect
    //Thread.sleep(200);

    // Check thread was interrupted
    fireEvent("beforeCheck");
    assertTrue(wtt._thrown instanceof InterruptedException);

    // Return object to the pool
    pool.returnObject(obj1);

    // Bug POOL-162 - check there is now an object in the pool
    pool.setMaxWait(10L);
    Object obj2 = null;
    try {
        obj2 = pool.borrowObject();
        assertNotNull(obj2);
    } catch (NoSuchElementException e) {
        // Not expected
        fail("NoSuchElementException not expected");
    }
    pool.returnObject(obj2);
    pool.close();
    this.tearDown();
}

From source file:mondrian.rolap.RolapConnectionPool.java

/**
 * Gets or creates a connection pool for a particular connect
 * specification./*w w  w.  j av a2s .  c om*/
 */
private synchronized ObjectPool getPool(Object key, ConnectionFactory connectionFactory) {
    ObjectPool connectionPool = mapConnectKeyToPool.get(key);
    if (connectionPool == null) {
        // use GenericObjectPool, which provides for resource limits
        connectionPool = new GenericObjectPool(null, // PoolableObjectFactory, can be null
                50, // max active
                GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // action when exhausted
                3000, // max wait (milli seconds)
                10, // max idle
                false, // test on borrow
                false, // test on return
                60000, // time between eviction runs (millis)
                5, // number to test on eviction run
                30000, // min evictable idle time (millis)
                true); // test while idle

        // create a PoolableConnectionFactory
        AbandonedConfig abandonedConfig = new AbandonedConfig();
        // flag to remove abandoned connections from pool
        abandonedConfig.setRemoveAbandoned(true);
        // timeout (seconds) before removing abandoned connections
        abandonedConfig.setRemoveAbandonedTimeout(300);
        // Flag to log stack traces for application code which abandoned a
        // Statement or Connection
        abandonedConfig.setLogAbandoned(true);
        PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
                // the connection factory
                connectionFactory,
                // the object pool
                connectionPool,
                // statement pool factory for pooling prepared statements,
                // or null for no pooling
                null,
                // validation query (must return at least 1 row e.g. Oracle:
                // select count(*) from dual) to test connection, can be
                // null
                null,
                // default "read only" setting for borrowed connections
                false,
                // default "auto commit" setting for returned connections
                true,
                // AbandonedConfig object configures how to handle abandoned
                // connections
                abandonedConfig);

        // "poolableConnectionFactory" has registered itself with
        // "connectionPool", somehow, so we don't need the value any more.
        Util.discard(poolableConnectionFactory);
        mapConnectKeyToPool.put(key, connectionPool);
    }
    return connectionPool;
}

From source file:com.jfinal.ext.plugin.redis.JedisPlugin.java

private void parseSetting(String key, String value) {
    if ("timeout".equalsIgnoreCase(key)) {
        timeout = Integer.valueOf(value);
    } else if ("password".equalsIgnoreCase(key)) {
        password = value;/*from www .  j a  v  a2s .  c o  m*/
    } else if ("host".equalsIgnoreCase(key)) {
        host = value;
    } else if ("maxactive".equalsIgnoreCase(key)) {
        maxactive = Integer.valueOf(value);
    } else if ("maxidle".equalsIgnoreCase(key)) {
        maxidle = Integer.valueOf(value);
    } else if ("maxwait".equalsIgnoreCase(key)) {
        maxwait = Integer.valueOf(value);
    } else if ("minevictableidletimemillis".equalsIgnoreCase(key)) {
        minevictableidletimemillis = Long.valueOf(value);
    } else if ("minidle".equalsIgnoreCase(key)) {
        minidle = Integer.valueOf(value);
    } else if ("numtestsperevictionrun".equalsIgnoreCase(key)) {
        numtestsperevictionrun = Integer.valueOf(value);
    } else if ("softminevictableidletimemillis".equalsIgnoreCase(key)) {
        softminevictableidletimemillis = Long.valueOf(value);
    } else if ("timebetweenevictionrunsmillis".equalsIgnoreCase(key)) {
        timebetweenevictionrunsmillis = Long.valueOf(value);
    } else if ("whenexhaustedaction".equalsIgnoreCase(key)) {
        if ("WHEN_EXHAUSTED_BLOCK".equalsIgnoreCase(value)) {
            whenexhaustedaction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else if ("WHEN_EXHAUSTED_FAIL".equalsIgnoreCase(value)) {
            whenexhaustedaction = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
        } else if ("WHEN_EXHAUSTED_GROW".equalsIgnoreCase(value)) {
            whenexhaustedaction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
        }
    } else if ("testwhileidle".equalsIgnoreCase(key)) {
        testwhileidle = Boolean.getBoolean(value);
    } else if ("testonreturn".equalsIgnoreCase(key)) {
        testonreturn = Boolean.getBoolean(value);
    } else if ("testonborrow".equalsIgnoreCase(key)) {
        testonborrow = Boolean.getBoolean(value);
    }
}