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

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

Introduction

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

Prototype

byte WHEN_EXHAUSTED_GROW

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

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 simply create a new object anyway.

Usage

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  w w w  .j  a  v  a  2 s.  c  o m
        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);
        }/*  ww  w .  ja  v a 2s.  c  o 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:de.xirp.db.XConnectionProvider.java

/**
 * This methos initializes the connection pool using the given
 * URL, user name and password.//w w  w  .j av a 2  s . c  o  m
 * 
 * @param url
 *            The db URL.
 * @param user
 *            The db user.
 * @param password
 *            The users password.
 */
private void initPool(String url, String user, String password) {

    connectionPool = new GenericObjectPool();
    connectionFactory = new DriverManagerConnectionFactory(url, user, password);
    poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null,
            false, true);
    dataSource = new PoolingDataSource(connectionPool);

    dataSource.setAccessToUnderlyingConnectionAllowed(false);

    connectionPool.setMaxActive(MAX_ACTIVE);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setMinIdle(MIN_IDLE);
    connectionPool.setTimeBetweenEvictionRunsMillis(EVICTION_TIME);
    connectionPool.setTestOnBorrow(true);
    connectionPool.setTestWhileIdle(false);
    connectionPool.setTestOnReturn(false);

    ds = dataSource;
}

From source file:edu.mayo.informatics.cts.CTSVAPI.sqlLite.refImpl.SQLStatements.java

private SQLStatements(String username, String password, String url, String driver) throws Exception {
    logger_.debug("Initializing sql and sql connections");

    JDBCConnectionDescriptor desc = getConnectionDescriptor();

    try {/*  w  w w. ja  v  a  2  s. co m*/
        desc.setDbDriver(driver);
    } catch (ClassNotFoundException e) {
        logger_.error("The driver for your sql connection was not found.  I tried to load " + driver);
        throw e;
    }
    desc.setDbUid(username);
    desc.setDbPwd(password);
    desc.setAutoCommit(true);
    desc.setDbUrl(url);
    desc.setUseUTF8(true);
    desc.setAutoRetryFailedConnections(true);

    //set up the pool
    JDBCConnectionPoolPolicy pol = getConnectionPoolPolicy();
    pol.maxActive = 4;
    pol.maxIdle = -1;
    pol.maxWait = -1;
    pol.minEvictableIdleTimeMillis = -1;
    pol.numTestsPerEvictionRun = 1;
    pol.testOnBorrow = false;
    pol.testOnReturn = false;
    pol.testWhileIdle = false;
    pol.timeBetweenEvictionRunsMillis = -1;
    pol.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    desc.setPingSQL("Select CodingSchemeName from codingScheme where CodingSchemeName='foobar'");

    // I need to know this to generate proper queries.
    String databaseName = this
            .getArbitraryStatement("Select CodingSchemeName from codingScheme where CodingSchemeName='foobar'")
            .getConnection().getMetaData().getDatabaseProductName();
    gSQLMod_ = new GenericSQLModifier(databaseName, true);
    initStatements();
}

From source file:edu.mayo.informatics.cts.CTSVAPI.sql.refImpl.SQLStatements.java

private SQLStatements(String username, String password, String url, String driver, String tablePrefix)
        throws Exception {
    logger_.debug("Initializing sql and sql connections");

    JDBCConnectionDescriptor desc = getConnectionDescriptor();

    try {/*from  ww  w . jav a  2s.  c o m*/
        desc.setDbDriver(driver);
    } catch (ClassNotFoundException e) {
        logger_.error("The driver for your sql connection was not found.  I tried to load " + driver);
        throw e;
    }
    desc.setDbUid(username);
    desc.setDbPwd(password);
    desc.setAutoCommit(true);
    desc.setDbUrl(url);
    desc.setUseUTF8(true);
    desc.setAutoRetryFailedConnections(true);

    // Connection pool parameters
    JDBCConnectionPoolPolicy pol = getConnectionPoolPolicy();
    pol.maxActive = 4;
    pol.maxIdle = -1;
    pol.maxWait = -1;
    pol.minEvictableIdleTimeMillis = -1;
    pol.numTestsPerEvictionRun = 1;
    pol.testOnBorrow = false;
    pol.testOnReturn = false;
    pol.testWhileIdle = false;
    pol.timeBetweenEvictionRunsMillis = -1;
    pol.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    desc.setPingSQL("Select CodingSchemeName from codingScheme where CodingSchemeName='foobar'");

    // I need to know this to generate proper queries.

    Connection conn = (Connection) getConnectionPool().borrowObject();

    String databaseName = conn.getMetaData().getDatabaseProductName();
    stc_ = new SQLTableUtilities(conn, tablePrefix).getSQLTableConstants();

    getConnectionPool().returnObject(conn);

    //need to override the like since the converter now creates case sensitive tables 
    //this forces a case insensitive search
    GenericSQLModifier.mySqlLikeOverride = "COLLATE latin1_swedish_ci LIKE";
    gSQLMod_ = new GenericSQLModifier(databaseName, false);
    initStatements();
}

From source file:edu.mayo.informatics.cts.CTSMAPI.refImpl.SQLStatements.java

private SQLStatements(String username, String password, String url, String driver) throws Exception {
    logger_.debug("Initializing sql and sql connections");

    JDBCConnectionDescriptor desc = getConnectionDescriptor();

    try {//w ww.j a  va 2  s.  co m
        desc.setDbDriver(driver);
    } catch (ClassNotFoundException e) {
        logger_.error("The driver for your sql connection was not found.  I tried to load " + driver);
        throw e;
    }
    desc.setDbUid(username);
    desc.setDbPwd(password);
    desc.setAutoCommit(true);
    desc.setDbUrl(url);
    desc.setUseUTF8(true);
    desc.setAutoRetryFailedConnections(true);

    //This sets it up to verify that the connection is up and working before a statement
    // is executed, among other things.
    JDBCConnectionPoolPolicy pol = getConnectionPoolPolicy();
    pol.maxActive = 4;
    pol.maxIdle = -1;
    pol.maxWait = -1;
    pol.minEvictableIdleTimeMillis = -1;
    pol.numTestsPerEvictionRun = 1;
    pol.testOnBorrow = false;
    pol.testOnReturn = false;
    pol.testWhileIdle = false;
    pol.timeBetweenEvictionRunsMillis = -1;
    pol.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW;
    desc.setPingSQL("Select ModelID from Model");

    Connection conn = (Connection) getConnectionPool().borrowObject();

    dbName_ = conn.getMetaData().getDatabaseProductName();

    getConnectionPool().returnObject(conn);

    initStatements();
}

From source file:com.flipkart.phantom.thrift.impl.ThriftProxy.java

/**
 * Initialize this ThriftProxy//from  w w w. j  av  a2 s .co  m
 */
public void init(TaskContext context) throws Exception {
    if (this.thriftServiceClass == null) {
        throw new AssertionError("The 'thriftServiceClass' may not be null");
    }
    if (this.processMap == null || this.processMap.isEmpty()) {
        throw new AssertionError(
                "ProcessFunctions not populated. Maybe The 'thriftServiceClass' is not a valid class?");
    }
    if (this.thriftTimeoutMillis == -1) { // implying none set
        throw new Exception("'thriftTimeoutMillis' must be set to a non-negative value!");
    }

    //Create pool
    this.socketPool = new GenericObjectPool<Socket>(new SocketObjectFactory(this), this.poolSize,
            GenericObjectPool.WHEN_EXHAUSTED_GROW, this.maxWait, this.maxIdle, this.minIdle, false, false,
            this.timeBetweenEvictionRunsMillis, GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN,
            GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, true);
}

From source file:com.iciql.test.IciqlSuite.java

/**
 * Open a new Db object. All connections are cached and re-used to eliminate
 * embedded database startup costs./*  w w  w  .  j  a  v  a 2  s  .com*/
 * 
 * @return a fresh Db object
 */
public static Db openNewDb() {
    String testUrl = System.getProperty("iciql.url", DEFAULT_TEST_DB.url);
    String testUser = System.getProperty("iciql.user", DEFAULT_TEST_DB.username);
    String testPassword = System.getProperty("iciql.password", DEFAULT_TEST_DB.password);

    Db db = null;
    PoolingDataSource dataSource = dataSources.get(testUrl);
    if (dataSource == null) {
        ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(testUrl, testUser,
                testPassword);
        GenericObjectPool pool = new GenericObjectPool();
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
        PoolableConnectionFactory factory = new PoolableConnectionFactory(connectionFactory, pool, null, null,
                false, true);
        dataSource = new PoolingDataSource(pool);
        dataSources.put(testUrl, dataSource);
        connectionFactories.put(testUrl, factory);
    }
    db = Db.open(dataSource);

    // drop views
    db.dropView(ProductView.class);
    db.dropView(ProductViewInherited.class);
    db.dropView(ProductViewFromQuery.class);
    db.dropView(ProductViewInheritedComplex.class);

    // drop tables
    db.dropTable(BooleanModel.class);
    db.dropTable(ComplexObject.class);
    db.dropTable(Customer.class);
    db.dropTable(DefaultValuesModel.class);
    db.dropTable(EnumIdModel.class);
    db.dropTable(EnumOrdinalModel.class);
    db.dropTable(EnumStringModel.class);
    db.dropTable(Order.class);
    db.dropTable(PrimitivesModel.class);
    db.dropTable(Product.class);
    db.dropTable(ProductAnnotationOnly.class);
    db.dropTable(ProductInheritedAnnotation.class);
    db.dropTable(ProductMixedAnnotation.class);
    db.dropTable(SupportedTypes.class);
    db.dropTable(JoinTest.UserId.class);
    db.dropTable(JoinTest.UserNote.class);
    db.dropTable(EnumsTest.BadEnums.class);
    db.dropTable(MultipleBoolsModel.class);
    db.dropTable(ProductAnnotationOnlyWithForeignKey.class);
    db.dropTable(CategoryAnnotationOnly.class);

    return db;
}

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  w w w . ja v  a 2s  .  c  om
    } 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);
    }
}

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

public void testWhenExhaustedGrow() throws Exception {
    pool.setMaxActive(1);// www.  ja v  a  2 s  .c  om
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    Object obj1 = pool.borrowObject();
    assertNotNull(obj1);
    Object obj2 = pool.borrowObject();
    assertNotNull(obj2);
    pool.returnObject(obj2);
    pool.returnObject(obj1);
    pool.close();
}