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

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

Introduction

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

Prototype

public GenericObjectPool(PoolableObjectFactory factory) 

Source Link

Document

Create a new GenericObjectPool using the specified factory.

Usage

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

public void checkEvict(boolean lifo) throws Exception {
    // yea this is hairy but it tests all the code paths in GOP.evict()
    final SimpleFactory factory = new SimpleFactory();
    final GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setSoftMinEvictableIdleTimeMillis(10);
    pool.setMinIdle(2);/*ww w .  j a  v a 2  s .c  o m*/
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    PoolUtils.prefill(pool, 5);
    pool.evict();
    factory.setEvenValid(false);
    factory.setOddValid(false);
    factory.setThrowExceptionOnActivate(true);
    pool.evict();
    PoolUtils.prefill(pool, 5);
    factory.setThrowExceptionOnActivate(false);
    factory.setThrowExceptionOnPassivate(true);
    pool.evict();
    factory.setThrowExceptionOnPassivate(false);
    factory.setEvenValid(true);
    factory.setOddValid(true);
    Thread.sleep(125);
    pool.evict();
    assertEquals(2, pool.getNumIdle());
}

From source file:com.nridge.core.ds.rdbms.SQLConnectionPool.java

private void create(Properties aProperties, String anAccount, String anPassword) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "create");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    String driverClassName = aProperties.getProperty("driverClassName");
    try {/*w  w  w. j a va 2s .  co m*/
        Class.forName(driverClassName).getConstructor().newInstance();
    } catch (Exception e) {
        throw new NSException(String.format("%s: %s", driverClassName, e.getMessage()), e);
    }

    String validationQuery = aProperties.getProperty("validationQuery");
    boolean isAutoCommit = StrUtl.stringToBoolean("defaultAutoCommit");

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(aProperties.getProperty("url"),
            anAccount, anPassword);
    GenericObjectPool connectionPool = new GenericObjectPool(null);

    // When you pass an ObjectPool into the PoolableConnectionFactory, it will automatically
    // register itself as the PoolableObjectFactory for that pool.

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, validationQuery, false, isAutoCommit);
    mDataSource = new PoolingDataSource(connectionPool);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:ch.rgw.tools.JdbcLink.java

/**
 * Verbindung zur Datenbank herstellen/*from  www . j av  a2  s.  com*/
 * 
 * TODO return value is always true because exception is thrown on error
 * 
 * @param user
 *            Username, kann null sein
 * @param password
 *            Passwort, kann null sein
 * @return errcode
 * 
 * @throws JdbcLinkException
 */
public boolean connect(String user, String password) {
    Exception cause = null;
    try {
        sUser = user;
        sPwd = password;
        Driver driver = (Driver) Class.forName(sDrv).newInstance();
        verMajor = driver.getMajorVersion();
        verMinor = driver.getMinorVersion();

        log.log(Level.INFO, "Loading database driver " + sDrv);
        log.log(Level.INFO, "Connecting with database " + sConn);

        //
        // First, we'll create a ConnectionFactory that the
        // pool will use to create Connections.
        //
        Properties properties = new Properties();
        properties.put("user", user);
        properties.put("password", password);

        ConnectionFactory connectionFactory = new DriverConnectionFactory(driver, sConn, properties);
        //
        // Next we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        connectionPool = new GenericObjectPool<Connection>(null);
        // configure the connection pool
        connectionPool.setMaxActive(32);
        connectionPool.setMinIdle(2);
        connectionPool.setMaxWait(10000);
        connectionPool.setTestOnBorrow(true);

        new PoolableConnectionFactory(connectionFactory, connectionPool, null, VALIDATION_QUERY, false, true);
        dataSource = new PoolingDataSource(connectionPool);

        // test establishing a connection
        Connection conn = dataSource.getConnection();
        conn.close();

        lastErrorCode = CONNECT_SUCCESS;
        lastErrorString = "Connect successful";
        log.log("Connect successful", Log.DEBUGMSG);
        return true;
    } catch (ClassNotFoundException ex) {
        lastErrorCode = CONNECT_CLASSNOTFOUND;
        lastErrorString = "Class not found exception: " + ex.getMessage();
        cause = ex;
    } catch (InstantiationException e) {
        lastErrorCode = CONNECT_UNKNOWN_ERROR;
        lastErrorString = "Instantiation exception: " + e.getMessage();
        cause = e;
    } catch (IllegalAccessException e) {
        lastErrorCode = CONNECT_UNKNOWN_ERROR;
        lastErrorString = "Illegal access exception: " + e.getMessage();
        cause = e;
    } catch (SQLException e) {
        lastErrorCode = CONNECT_UNKNOWN_ERROR;
        lastErrorString = "SQL exception: " + e.getMessage();
        cause = e;
    } catch (IllegalStateException e) {
        lastErrorCode = CONNECT_UNKNOWN_ERROR;
        lastErrorString = "Illegal state exception: " + e.getMessage();
        cause = e;
    }
    throw JdbcLinkExceptionTranslation.translateException("Connect failed: " + lastErrorString, cause);
}

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

private void checkEvictionOrder(boolean lifo) throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(2);//  w w w.  j  a va2 s.  c  o  m
    pool.setMinEvictableIdleTimeMillis(100);
    pool.setLifo(lifo);
    for (int i = 0; i < 5; i++) {
        pool.addObject();
        Thread.sleep(100);
    }
    // Order, oldest to youngest, is "0", "1", ...,"4"
    pool.evict(); // Should evict "0" and "1"
    Object obj = pool.borrowObject();
    assertTrue("oldest not evicted", !obj.equals("0"));
    assertTrue("second oldest not evicted", !obj.equals("1"));
    // 2 should be next out for FIFO, 4 for LIFO
    assertEquals("Wrong instance returned", lifo ? "4" : "2", obj);

    // Two eviction runs in sequence
    factory = new SimpleFactory();
    pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(2);
    pool.setMinEvictableIdleTimeMillis(100);
    pool.setLifo(lifo);
    for (int i = 0; i < 5; i++) {
        pool.addObject();
        Thread.sleep(100);
    }
    pool.evict(); // Should evict "0" and "1"
    pool.evict(); // Should evict "2" and "3"
    obj = pool.borrowObject();
    assertEquals("Wrong instance remaining in pool", "4", obj);
}

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

private void checkEvictorVisiting(boolean lifo) throws Exception {
    VisitTrackerFactory factory = new VisitTrackerFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(2);/* ww w.j  a  v a 2  s . com*/
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // Visit oldest 2 - 0 and 1
    Object obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO will move 0 and 1 to end
    // LIFO, 7 out, then in, then out, then in
    pool.evict(); // Should visit 2 and 3 in either case
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() >= 4) {
            assertEquals("Unexpected instance visited " + tracker.getId(), 0, tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        }
    }

    factory = new VisitTrackerFactory();
    pool = new GenericObjectPool(factory);
    pool.setNumTestsPerEvictionRun(3);
    pool.setMinEvictableIdleTimeMillis(-1);
    pool.setTestWhileIdle(true);
    pool.setLifo(lifo);
    pool.setTestOnReturn(false);
    pool.setTestOnBorrow(false);
    for (int i = 0; i < 8; i++) {
        pool.addObject();
    }
    pool.evict(); // 0, 1, 2
    pool.evict(); // 3, 4, 5
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    obj = pool.borrowObject();
    pool.returnObject(obj);
    // borrow, return, borrow, return
    // FIFO 3,4,5,6,7,0,1,2
    // LIFO 7,6,5,4,3,2,1,0
    // In either case, pointer should be at 6
    pool.evict();
    // Should hit 6,7,0 - 0 for second time
    for (int i = 0; i < 8; i++) {
        VisitTracker tracker = (VisitTracker) pool.borrowObject();
        if (tracker.getId() != 0) {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 1,
                    tracker.getValidateCount());
        } else {
            assertEquals("Instance " + tracker.getId() + " visited wrong number of times.", 2,
                    tracker.getValidateCount());
        }
    }
    // Randomly generate a pools with random numTests
    // and make sure evictor cycles through elements appropriately
    int[] smallPrimes = { 2, 3, 5, 7 };
    Random random = new Random();
    random.setSeed(System.currentTimeMillis());
    for (int i = 0; i < 4; i++) {
        pool.setNumTestsPerEvictionRun(smallPrimes[i]);
        for (int j = 0; j < 5; j++) {
            pool = new GenericObjectPool(factory);
            pool.setNumTestsPerEvictionRun(3);
            pool.setMinEvictableIdleTimeMillis(-1);
            pool.setTestWhileIdle(true);
            pool.setLifo(lifo);
            pool.setTestOnReturn(false);
            pool.setTestOnBorrow(false);
            pool.setMaxIdle(-1);
            int instanceCount = 10 + random.nextInt(20);
            pool.setMaxActive(instanceCount);
            for (int k = 0; k < instanceCount; k++) {
                pool.addObject();
            }

            // Execute a random number of evictor runs
            int runs = 10 + random.nextInt(50);
            for (int k = 0; k < runs; k++) {
                pool.evict();
            }

            // Number of times evictor should have cycled through the pool
            int cycleCount = (runs * pool.getNumTestsPerEvictionRun()) / instanceCount;

            // Look at elements and make sure they are visited cycleCount
            // or cycleCount + 1 times
            VisitTracker tracker = null;
            int visitCount = 0;
            for (int k = 0; k < instanceCount; k++) {
                tracker = (VisitTracker) pool.borrowObject();
                assertTrue(pool.getNumActive() <= pool.getMaxActive());
                visitCount = tracker.getValidateCount();
                assertTrue(visitCount >= cycleCount && visitCount <= cycleCount + 1);
            }
        }
    }
}

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

public void testExceptionOnPassivateDuringReturn() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    Object obj = pool.borrowObject();
    factory.setThrowExceptionOnPassivate(true);
    pool.returnObject(obj);/*from  w w  w . j a  va 2  s .co  m*/
    assertEquals(0, pool.getNumIdle());
    pool.close();
}

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

public void testExceptionOnDestroyDuringBorrow() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    factory.setThrowExceptionOnDestroy(true);
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setTestOnBorrow(true);/* ww  w . j  av  a  2  s.c  om*/
    pool.borrowObject();
    factory.setValid(false); // Make validation fail on next borrow attempt
    try {
        pool.borrowObject();
        fail("Expecting NoSuchElementException");
    } catch (NoSuchElementException ex) {
        // expected
    }
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

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

public void testExceptionOnDestroyDuringReturn() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    factory.setThrowExceptionOnDestroy(true);
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setTestOnReturn(true);/*www.  j ava 2  s  .  c om*/
    Object obj1 = pool.borrowObject();
    pool.borrowObject();
    factory.setValid(false); // Make validation fail
    pool.returnObject(obj1);
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

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

public void testExceptionOnActivateDuringBorrow() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    Object obj1 = pool.borrowObject();
    Object obj2 = pool.borrowObject();
    pool.returnObject(obj1);//from w ww  .  j a  v a  2  s  .c o m
    pool.returnObject(obj2);
    factory.setThrowExceptionOnActivate(true);
    factory.setEvenValid(false);
    // Activation will now throw every other time
    // First attempt throws, but loop continues and second succeeds
    Object obj = pool.borrowObject();
    assertEquals(1, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());

    pool.returnObject(obj);
    factory.setValid(false);
    // Validation will now fail on activation when borrowObject returns
    // an idle instance, and then when attempting to create a new instance
    try {
        obj1 = pool.borrowObject();
        fail("Expecting NoSuchElementException");
    } catch (NoSuchElementException ex) {
        // expected
    }
    assertEquals(0, pool.getNumActive());
    assertEquals(0, pool.getNumIdle());
}

From source file:ca.gnewton.lusql.core.LuSql.java

void initPools() {
    if (docPoolFlag) {
        df = new DocFactory();
        docPool = new GenericObjectPool(df);
        docPool.setLifo(true);/*from  w  w w .j a v a  2  s .  c o  m*/
        docPool.setMaxActive(-1);
        docPool.setMaxIdle(1000);
    }

    if (addDocPoolFlag) {
        // AddDocument pool
        AddDocumentFactory adf = new AddDocumentFactory();
        addPool = new GenericObjectPool(adf);
        addPool.setLifo(true);
        addPool.setMaxActive(-1);
        addPool.setMaxIdle(8);
    }

}