Example usage for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_FAIL

List of usage examples for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_FAIL

Introduction

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

Prototype

byte WHEN_EXHAUSTED_FAIL

To view the source code for org.apache.commons.pool.impl GenericKeyedObjectPool WHEN_EXHAUSTED_FAIL.

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 fail, throwing a NoSuchElementException .

Usage

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

public void testNegativeMaxActive() throws Exception {
    pool.setMaxActive(-1);//from  w  ww .  j  a  va 2s. c o  m
    pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);
    Object obj = pool.borrowObject("");
    assertEquals("0", obj);
    pool.returnObject("", obj);
}

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  va  2s .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:edu.illinois.enforcemop.examples.apache.pool.TestGenericKeyedObjectPool.java

public void testMaxActive() throws Exception {
    pool.setMaxActive(3);/*from   w w  w . ja va 2s .c  o m*/
    pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);

    pool.borrowObject("");
    pool.borrowObject("");
    pool.borrowObject("");
    try {
        pool.borrowObject("");
        fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
        // expected
    }
}

From source file:com.servoy.extensions.plugins.rest_ws.RestWSPlugin.java

synchronized KeyedObjectPool getClientPool() {
    if (clientPool == null) {
        byte exchaustedAction;
        int poolSize;
        if (ApplicationServerRegistry.get().isDeveloperStartup()) {
            // in developer multiple clients do not work well with debugger
            poolSize = 1;/*  w w w .j  av a  2 s  .  c o m*/
            exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
        } else {
            try {
                poolSize = Integer.parseInt(application.getSettings()
                        .getProperty(CLIENT_POOL_SIZE_PROPERTY, "" + CLIENT_POOL_SIZE_DEFAULT).trim());
            } catch (NumberFormatException nfe) {
                poolSize = CLIENT_POOL_SIZE_DEFAULT;
            }
            String exchaustedActionCode = application.getSettings()
                    .getProperty(CLIENT_POOL_EXCHAUSTED_ACTION_PROPERTY);
            if (exchaustedActionCode != null)
                exchaustedActionCode = exchaustedActionCode.trim();
            if (ACTION_FAIL.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_FAIL);
            } else if (ACTION_GROW.equalsIgnoreCase(exchaustedActionCode)) {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_GROW);
            } else {
                exchaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK;
                if (log.isDebugEnabled())
                    log.debug("Client pool, exchaustedAction=" + ACTION_BLOCK);
            }
        }
        if (log.isDebugEnabled())
            log.debug("Creating client pool, maxSize=" + poolSize);
        clientPool = new GenericKeyedObjectPool(new BaseKeyedPoolableObjectFactory() {
            @Override
            public Object makeObject(Object key) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("creating new session client for solution '" + key + '\'');
                String solutionName = (String) key;
                String[] solOpenArgs = SOLUTION_OPEN_METHOD_ARGS;

                String[] arr = solutionName.split(":");
                if (arr.length == 2) {
                    solutionName = arr[0];
                    solOpenArgs = Utils.arrayJoin(SOLUTION_OPEN_METHOD_ARGS, new String[] { "nodebug" });
                }
                return HeadlessClientFactory.createHeadlessClient(solutionName, solOpenArgs);
            }

            @Override
            public boolean validateObject(Object key, Object obj) {
                IHeadlessClient client = ((IHeadlessClient) obj);
                if (client.getPluginAccess().isInDeveloper()) {
                    String solutionName = (String) key;
                    if (solutionName.contains(":"))
                        solutionName = solutionName.split(":")[0];

                    if (!solutionName.equals(((IHeadlessClient) obj).getPluginAccess().getSolutionName())) {
                        try {
                            client.closeSolution(true);
                            client.loadSolution(solutionName);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                }
                boolean valid = client.isValid();
                if (log.isDebugEnabled())
                    log.debug("Validated session client for solution '" + key + "', valid = " + valid);
                return valid;
            }

            @Override
            public void destroyObject(Object key, Object obj) throws Exception {
                if (log.isDebugEnabled())
                    log.debug("Destroying session client for solution '" + key + "'");
                IHeadlessClient client = ((IHeadlessClient) obj);
                try {
                    client.shutDown(true);
                } catch (Exception e) {
                    Debug.error(e);
                }
            }
        }, poolSize);
        clientPool.setTestOnBorrow(true);
        clientPool.setWhenExhaustedAction(exchaustedAction);
        clientPool.setMaxIdle(poolSize); // destroy objects when pool has grown
    }
    return clientPool;
}

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

public void testMaxTotal() throws Exception {
    pool.setMaxActive(2);//  w  w  w .  j  a va2  s .  c om
    pool.setMaxTotal(3);
    pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);

    Object o1 = pool.borrowObject("a");
    assertNotNull(o1);
    Object o2 = pool.borrowObject("a");
    assertNotNull(o2);
    Object o3 = pool.borrowObject("b");
    assertNotNull(o3);
    try {
        pool.borrowObject("c");
        fail("Expected NoSuchElementException");
    } catch (NoSuchElementException e) {
        // expected
    }

    assertEquals(0, pool.getNumIdle());

    pool.returnObject("b", o3);
    assertEquals(1, pool.getNumIdle());
    assertEquals(1, pool.getNumIdle("b"));

    Object o4 = pool.borrowObject("b");
    assertNotNull(o4);
    assertEquals(0, pool.getNumIdle());
    assertEquals(0, pool.getNumIdle("b"));

    pool.setMaxTotal(4);
    Object o5 = pool.borrowObject("b");
    assertNotNull(o5);

    assertEquals(2, pool.getNumActive("a"));
    assertEquals(2, pool.getNumActive("b"));
    assertEquals(pool.getMaxTotal(), pool.getNumActive("b") + pool.getNumActive("b"));
    assertEquals(pool.getNumActive(), pool.getMaxTotal());
}

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

public void testSettersAndGetters() throws Exception {
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool();
    {//from w w  w . j  ava 2s.  c  o m
        pool.setFactory(new SimpleFactory());
    }
    {
        pool.setMaxActive(123);
        assertEquals(123, pool.getMaxActive());
    }
    {
        pool.setMaxIdle(12);
        assertEquals(12, pool.getMaxIdle());
    }
    {
        pool.setMaxWait(1234L);
        assertEquals(1234L, pool.getMaxWait());
    }
    {
        pool.setMinEvictableIdleTimeMillis(12345L);
        assertEquals(12345L, pool.getMinEvictableIdleTimeMillis());
    }
    {
        pool.setNumTestsPerEvictionRun(11);
        assertEquals(11, pool.getNumTestsPerEvictionRun());
    }
    {
        pool.setTestOnBorrow(true);
        assertTrue(pool.getTestOnBorrow());
        pool.setTestOnBorrow(false);
        assertTrue(!pool.getTestOnBorrow());
    }
    {
        pool.setTestOnReturn(true);
        assertTrue(pool.getTestOnReturn());
        pool.setTestOnReturn(false);
        assertTrue(!pool.getTestOnReturn());
    }
    {
        pool.setTestWhileIdle(true);
        assertTrue(pool.getTestWhileIdle());
        pool.setTestWhileIdle(false);
        assertTrue(!pool.getTestWhileIdle());
    }
    {
        pool.setTimeBetweenEvictionRunsMillis(11235L);
        assertEquals(11235L, pool.getTimeBetweenEvictionRunsMillis());
    }
    {
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_FAIL, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_GROW, pool.getWhenExhaustedAction());
    }
}

From source file:org.agnitas.dao.LoggingEnhBasicDataSource.java

/**
  * <p>Create (if necessary) and return the internal data source we are
  * using to manage our connections.</p>
  */* w  ww .  ja  va 2 s . c  o m*/
  * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
  * "double checked locking" idiom in an attempt to avoid synchronizing
  * on every single call to this method.  However, this idiom fails to
  * work correctly in the face of some optimizations that are legal for
  * a JVM to perform.</p>
  *
  * @exception SQLException if the object pool cannot be created.
  */
protected synchronized DataSource createDataSource() throws SQLException {

    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }

    logger.error("-------------------------------------------- Create new datasource");
    // Load the JDBC driver class
    if (driverClassName != null) {
        try {
            Class.forName(driverClassName);
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }

    // Create a JDBC driver instance
    Driver driver = null;
    try {
        driver = DriverManager.getDriver(url);
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '"
                + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }

    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }

    // Create an object pool to contain our active connections
    connectionPool = new LoggingObjectPool();
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key) 
                maxOpenPreparedStatements);
    }

    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        logger.error("DBCP DataSource configured without a 'username'");
    }

    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        logger.error("DBCP DataSource configured without a 'password'");
    }

    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url,
            connectionProperties);

    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool,
                statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit,
                defaultTransactionIsolation, defaultCatalog, null);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }

    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource)
            .setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);

    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }

    return dataSource;
}

From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java

protected KeyedObjectPoolFactory createStatementPoolFactory(JdbcConnectionDescriptor jcd) {
    final String platform = jcd.getDbms();
    if (platform.startsWith("Oracle9i")) {
        // mkalen: let the platform set Oracle-specific statement pooling
        return null;
    }/*from w w  w.j  a va 2 s.  c o  m*/

    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties();
    final String poolStmtParam = properties.getProperty(PARAM_NAME_POOL_STATEMENTS);
    if (poolStmtParam != null && Boolean.valueOf(poolStmtParam).booleanValue()) {
        int maxOpenPreparedStatements = GenericKeyedObjectPool.DEFAULT_MAX_TOTAL;
        final String maxOpenPrepStmtString = properties.getProperty(PARAM_NAME_STATEMENT_POOL_MAX_TOTAL);
        if (maxOpenPrepStmtString != null) {
            maxOpenPreparedStatements = Integer.parseInt(maxOpenPrepStmtString);
        }
        // Use the same values as Commons DBCP BasicDataSource
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, -1, // unlimited maxActive (per key)
                GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxWait
                1, // maxIdle (per key)
                maxOpenPreparedStatements);
    }
    return statementPoolFactory;
}

From source file:org.apereo.portal.xml.xpath.XPathPoolImpl.java

public XPathPoolImpl(NamespaceContext namespaceContext) {
    this.namespaceContext = namespaceContext;

    this.xpathExpressionfactory = new XPathExpressionFactory(this.namespaceContext, variableResolver);

    this.pool = new GenericKeyedObjectPool(xpathExpressionfactory);
    this.pool.setMaxActive(500);
    this.pool.setMaxIdle(500);
    this.pool.setTimeBetweenEvictionRunsMillis(TimeUnit.SECONDS.toMillis(60));
    this.pool.setMinEvictableIdleTimeMillis(TimeUnit.MINUTES.toMillis(5));
    this.pool.setNumTestsPerEvictionRun(this.pool.getMaxIdle() / 9);
    this.pool.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL);
}

From source file:org.glassfish.grizzly.memcached.pool.BaseObjectPoolBenchmark.java

@Test
public void testBenchmarkingInMultiThreads() {
    final int threadCount = 1000;
    final int poolSize = 150;
    final KeyedPoolableObjectFactory<String, String> apacheFactory = new KeyedPoolableObjectFactory<String, String>() {
        private static final String VALUE_NAME = "value";
        private int id;
        private int count;

        @Override/*from w  w  w.j av a 2  s  . c  om*/
        public synchronized String makeObject(String s) throws Exception {
            count++;
            return VALUE_NAME + ++id;
        }

        @Override
        public synchronized void destroyObject(String s, String s1) throws Exception {
            count--;
        }

        @Override
        public boolean validateObject(String s, String s1) {
            return true;
        }

        @Override
        public void activateObject(String s, String s1) throws Exception {
        }

        @Override
        public void passivateObject(String s, String s1) throws Exception {
        }
    };
    final GenericKeyedObjectPool<String, String> apachePool = new GenericKeyedObjectPool<String, String>(
            apacheFactory, poolSize, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, poolSize, poolSize,
            poolSize, false, false, 1000 * 60 * 60, 0, 1000 * 60 * 60, false);

    final ConcurrentLinkedQueue<String> borrowObjects = new ConcurrentLinkedQueue<String>();
    final CountDownLatch startFlag = new CountDownLatch(1);
    final CountDownLatch finishFlag = new CountDownLatch(threadCount * 2);
    final AtomicInteger exceptionCnt = new AtomicInteger();
    final AtomicInteger successCnt = new AtomicInteger();
    for (int i = 0; i < threadCount; i++) {
        final Thread borrowThread = new Thread() {
            @Override
            public void run() {
                try {
                    startFlag.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                for (int j = 0; j < 30; j++) {
                    try {
                        final String object = apachePool.borrowObject("key");
                        Assert.assertNotNull(object);
                        successCnt.incrementAndGet();
                        Assert.assertTrue(borrowObjects.offer(object));
                    } catch (Exception ignore) {
                        exceptionCnt.incrementAndGet();
                    }
                }
                finishFlag.countDown();
            }
        };
        borrowThread.start();

        final Thread returnThread = new Thread() {
            @Override
            public void run() {
                try {
                    startFlag.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                for (int j = 0; j < 30; j++) {
                    try {
                        final String object = borrowObjects.poll();
                        if (object != null) {
                            apachePool.returnObject("key", object);
                        }
                    } catch (Exception e) {
                        Assert.fail(e.getMessage());
                    }
                }
                finishFlag.countDown();
            }
        };
        returnThread.start();
    }
    long startTime = System.currentTimeMillis();
    startFlag.countDown();
    try {
        finishFlag.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    logger.info("apache common-pool elapse = {}", (System.currentTimeMillis() - startTime));
    try {
        logger.info("apache common-pool max gen-id = {}", apacheFactory.makeObject("key"));
    } catch (Exception ignore) {
    }
    logger.info("apache common-pool success counts = {}", successCnt.get());
    logger.info("apache common-pool exception counts = {}", exceptionCnt.get());

    try {
        apachePool.close();
    } catch (Exception ignore) {
    }

    // grizzly
    final PoolableObjectFactory<String, String> grizzlyFactory = new PoolableObjectFactory<String, String>() {
        private static final String VALUE_NAME = "value";
        private int id;
        private int count;

        @Override
        public synchronized String createObject(String s) throws Exception {
            count++;
            return VALUE_NAME + ++id;
        }

        @Override
        public synchronized void destroyObject(String s, String s1) throws Exception {
            count--;
        }

        @Override
        public boolean validateObject(String s, String s1) {
            return true;
        }
    };
    final BaseObjectPool.Builder<String, String> builder = new BaseObjectPool.Builder<String, String>(
            grizzlyFactory);
    builder.disposable(false);
    builder.keepAliveTimeoutInSecs(-1);
    builder.borrowValidation(false);
    builder.returnValidation(false);
    builder.max(poolSize);
    builder.min(poolSize);
    final ObjectPool<String, String> grizzlyPool = builder.build();

    final ConcurrentLinkedQueue<String> borrowObjects2 = new ConcurrentLinkedQueue<String>();
    final CountDownLatch startFlag2 = new CountDownLatch(1);
    final CountDownLatch finishFlag2 = new CountDownLatch(threadCount * 2);
    final AtomicInteger exceptionCnt2 = new AtomicInteger();
    final AtomicInteger successCnt2 = new AtomicInteger();
    for (int i = 0; i < threadCount; i++) {
        final Thread borrowThread = new Thread() {
            @Override
            public void run() {
                try {
                    startFlag2.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                for (int j = 0; j < 30; j++) {
                    try {
                        final String object = grizzlyPool.borrowObject("key", 0);
                        Assert.assertNotNull(object);
                        successCnt2.incrementAndGet();
                        Assert.assertTrue(borrowObjects2.offer(object));
                    } catch (Exception ignore) {
                        exceptionCnt2.incrementAndGet();
                    }
                }
                finishFlag2.countDown();
            }
        };
        borrowThread.start();

        final Thread returnThread = new Thread() {
            @Override
            public void run() {
                try {
                    startFlag2.await();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
                for (int j = 0; j < 30; j++) {
                    try {
                        final String object = borrowObjects2.poll();
                        if (object != null) {
                            grizzlyPool.returnObject("key", object);
                        }
                    } catch (Exception e) {
                        Assert.fail(e.getMessage());
                    }
                }
                finishFlag2.countDown();
            }
        };
        returnThread.start();
    }
    startTime = System.currentTimeMillis();
    startFlag2.countDown();
    try {
        finishFlag2.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    logger.info("grizzly pool elapse = {}", (System.currentTimeMillis() - startTime));
    try {
        logger.info("grizzly pool max gen-id = {}", grizzlyFactory.createObject("key"));
    } catch (Exception ignore) {
    }
    logger.info("grizzly pool success counts = {}", successCnt2.get());
    logger.info("grizzly pool exception counts= {}", exceptionCnt2.get());

    grizzlyPool.destroy();
}