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.tdclighthouse.prototype.rmi.RepositoryConnector.java

private Config getPoolConfig() {
    if (config == null) {
        config = new Config();
        config.maxActive = 10;/*  www .j a v  a2 s  .  c  o  m*/
        config.maxIdle = 1;
        config.maxWait = 5000L;
        config.minIdle = 1;
        config.softMinEvictableIdleTimeMillis = 300000L;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    }
    return config;
}

From source file:edu.amc.sakai.user.PoolingLdapConnectionManager.java

/**
 * {@inheritDoc}/*from w ww  .ja  va 2s .c  o m*/
 */
public void init() {
    super.init();

    if (pool != null) {
        return;
    }

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

    Config poolConfig = new Config();
    poolConfig.maxActive = getConfig().getPoolMaxConns();
    poolConfig.maxIdle = getConfig().getPoolMaxConns();
    poolConfig.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
    poolConfig.maxWait = POOL_MAX_WAIT;
    poolConfig.testOnBorrow = true;
    poolConfig.testOnReturn = false;

    pool = new GenericObjectPool(factory, poolConfig);
}

From source file:it.greenvulcano.gvesb.j2ee.db.connections.impl.DriverPoolConnectionBuilder.java

public void init(Node node) throws GVDBException {
    try {//from  ww  w  .jav  a 2  s .c  o  m
        name = XMLConfig.get(node, "@name");

        user = XMLConfig.get(node, "@user", null);
        password = XMLConfig.getDecrypted(node, "@password", null);
        url = XMLConfig.get(node, "@url");
        try {
            debugJDBCConn = Boolean.getBoolean(
                    "it.greenvulcano.gvesb.j2ee.db.connections.impl.ConnectionBuilder.debugJDBCConn");
        } catch (Exception exc) {
            debugJDBCConn = false;
        }

        Node poolNode = XMLConfig.getNode(node, "PoolParameters");
        connectionPool = new GenericObjectPool(null);
        connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
        connectionPool.setMaxWait(XMLConfig.getLong(poolNode, "@maxWait", 30) * 1000);

        connectionPool.setMinIdle(XMLConfig.getInteger(poolNode, "@minIdle", 5));
        connectionPool.setMaxIdle(XMLConfig.getInteger(poolNode, "@maxIdle", 10));
        connectionPool.setMaxActive(XMLConfig.getInteger(poolNode, "@maxActive", 15));
        connectionPool.setTimeBetweenEvictionRunsMillis(
                XMLConfig.getLong(poolNode, "@timeBetweenEvictionRuns", 300) * 1000);
        connectionPool.setMinEvictableIdleTimeMillis(
                XMLConfig.getLong(poolNode, "@minEvictableIdleTime", 300) * 1000);
        connectionPool.setNumTestsPerEvictionRun(XMLConfig.getInteger(poolNode, "@numTestsPerEvictionRun", 3));
        if (XMLConfig.exists(poolNode, "validationQuery")) {
            validationQuery = XMLConfig.get(poolNode, "validationQuery");
        }
    } catch (Exception exc) {
        throw new GVDBException("DriverPoolConnectionBuilder - Initialization error", exc);
    }

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password);
    new PoolableConnectionFactory(connectionFactory, connectionPool, null, validationQuery, false, true);

    dataSource = new PoolingDataSource(connectionPool);

    logger.debug("Crated DriverPoolConnectionBuilder(" + name + "). - user: " + user
            + " - password: ********* - url: " + url + " - Pool: [" + connectionPool.getMinIdle() + "/"
            + connectionPool.getMaxIdle() + "/" + connectionPool.getMaxActive() + "]");
}

From source file:gov.lanl.util.DBCPUtils.java

/**
 * Set-up a DBCP DataSource from core connection properties.
 * @param connectURI jdbc connection uri
 * @param jdbcDriverName qualified classpath to jdbc driver for database
 * @param username database user account
 * @param password database password/*from  w ww . j av a2  s . co m*/
 * @param maxActive max simultaneous db connections (default: 50)
 * @param maxIdle max idle db connections (default: 10)
 */
public static DataSource setupDataSource(String connectURI, String jdbcDriverName, String username,
        String password, int maxActive, int maxIdle) throws Exception {
    try {
        java.lang.Class.forName(jdbcDriverName).newInstance();
    } catch (Exception e) {
        log.error(
                "Error when attempting to obtain DB Driver: " + jdbcDriverName + " on " + new Date().toString(),
                e);
        throw new ResolverException(e);
    }

    if (maxActive <= 0)
        maxActive = 50;
    if (maxIdle <= 0)
        maxIdle = 10;

    GenericObjectPool connectionPool = new GenericObjectPool(null, // PoolableObjectFactory, can be null
            maxActive, // max active
            GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // action when exhausted
            3000, // max wait (milli seconds)
            maxIdle, // 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
    );

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username, password);

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    PoolingDataSource dataSource = new PoolingDataSource(connectionPool);

    return dataSource;
}

From source file:com.nxttxn.vramel.components.rabbitMQ.RabbitMQProducer.java

/**
 * Open connection and initialize channel pool
 *//*from w  w w  .  j a v  a 2s  .  co m*/
private void openConnectionAndChannelPool() throws Exception {
    logger.trace("Creating connection...");
    this.conn = getEndpoint().connect(executorService);
    logger.debug("Created connection: {}", conn);

    logger.trace("Creating channel pool...");
    channelPool = new GenericObjectPool<Channel>(new PoolableChannelFactory(this.conn),
            getEndpoint().getChannelPoolMaxSize(), GenericObjectPool.WHEN_EXHAUSTED_BLOCK,
            getEndpoint().getChannelPoolMaxWait());
    if (getEndpoint().isDeclare()) {
        execute(new ChannelCallback<Void>() {
            @Override
            public Void doWithChannel(Channel channel) throws Exception {
                getEndpoint().declareExchangeAndQueue(channel);
                return null;
            }
        });
    }
}

From source file:de.hybris.platform.test.ThreadPoolTest.java

@Test
public void testTransactionCleanUpSimple()
        throws InterruptedException, BrokenBarrierException, TimeoutException {
    final boolean flagBefore = Config.getBoolean("transaction.monitor.begin", false);
    Config.setParameter("transaction.monitor.begin", "true");
    ThreadPool pool = null;//from  www .  j a  v a2 s  .c o m
    try {
        pool = new ThreadPool(Registry.getCurrentTenantNoFallback().getTenantID(), 1);

        final GenericObjectPool.Config config = new GenericObjectPool.Config();
        config.maxActive = 1;
        config.maxIdle = 1;
        config.maxWait = -1;
        config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
        config.testOnBorrow = true;
        config.testOnReturn = true;
        config.timeBetweenEvictionRunsMillis = 30 * 1000; // keep idle threads for at most 30 sec
        pool.setConfig(config);

        final CyclicBarrier gate = new CyclicBarrier(2);
        final AtomicReference<Throwable> threadError = new AtomicReference<Throwable>();
        final AtomicReference<RecordingTransaction> threadTransaction = new AtomicReference<ThreadPoolTest.RecordingTransaction>();
        final PoolableThread thread1 = pool.borrowThread();
        thread1.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final Transaction tx = new RecordingTransaction();
                    tx.activateAsCurrentTransaction();
                    tx.begin();
                    tx.begin(); // second time
                    tx.begin(); // third time
                    assertTrue(tx.isRunning());
                    assertEquals(3, tx.getOpenTransactionCount());
                    threadTransaction.set((RecordingTransaction) tx);
                    gate.await(10, TimeUnit.SECONDS);
                } catch (final Throwable t) {
                    threadError.set(t);
                }
            }
        });
        gate.await(10, TimeUnit.SECONDS);
        assertNull(threadError.get());
        // busy waiting for correct number of rollbacks - at the moment there is no hook for a better solution
        final RecordingTransaction tx = threadTransaction.get();
        final long maxWait = System.currentTimeMillis() + (15 * 1000);
        while (tx.rollbackCounter.get() < 3 && System.currentTimeMillis() < maxWait) {
            Thread.sleep(100);
        }
        assertEquals(3, tx.rollbackCounter.get());

        final PoolableThread thread2 = pool.borrowThread();
        assertNotSame(thread1, thread2);
    } finally {
        if (pool != null) {
            try {
                pool.close();
            } catch (final Exception e) {
                // can't help it
            }
        }
        Config.setParameter("transaction.monitor.begin", BooleanUtils.toStringTrueFalse(flagBefore));
    }
}

From source file:com.jumptap.h2redis.RedisHMRecordWriter.java

private boolean init(String host, int port, String pw, int db, long maxWait) {
    try {//w  w  w .j  av  a 2  s .co m
        JedisPoolConfig conf = new JedisPoolConfig();
        conf.setMaxWait(maxWait);
        conf.setTestWhileIdle(true);
        conf.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);

        // 2 x the number of cores
        conf.setMaxActive(Runtime.getRuntime().availableProcessors() * 2);
        this.pool = new JedisPool(conf, host, port, Protocol.DEFAULT_TIMEOUT, pw, db);
        return ping();
    } catch (Exception ex) {
        throw new RuntimeException("Unable to connect to cache.", ex);
    }
}

From source file:com.cyberway.issue.io.WriterPool.java

/**
 * Constructor/*from ww  w.  ja  v  a  2  s.co m*/
 * @param serial  Used to generate unique filename sequences
 * @param factory Factory that knows how to make a {@link WriterPoolMember}.
 * @param settings Settings for this pool.
 * @param poolMaximumActive
 * @param poolMaximumWait
 */
public WriterPool(final AtomicInteger serial, final BasePoolableObjectFactory factory,
        final WriterPoolSettings settings, final int poolMaximumActive, final int poolMaximumWait) {
    logger.info("Initial configuration:" + " prefix=" + settings.getPrefix() + ", suffix="
            + settings.getSuffix() + ", compress=" + settings.isCompressed() + ", maxSize="
            + settings.getMaxSize() + ", maxActive=" + poolMaximumActive + ", maxWait=" + poolMaximumWait);
    this.settings = settings;
    this.pool = new FairGenericObjectPool(factory, poolMaximumActive, GenericObjectPool.WHEN_EXHAUSTED_BLOCK,
            poolMaximumWait, NO_MAX_IDLE);
    this.serialNo = serial;
}

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

@Test
public void testWhenExhaustedBlockInterruptImproved() throws Exception {
    this.setUp();
    pool.setMaxActive(1);//www.  ja v  a2  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
    NonWaitingTestThread nwtt = new NonWaitingTestThread(pool);
    nwtt.start();
    // Give wtt time to start
    Thread.sleep(200);
    nwtt.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
        if (nwtt._thrown instanceof InterruptedException) {
            fail("NoSuchElementException not expected");
        }

    }
    pool.returnObject(obj2);
    pool.close();
}

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

public void testWhenExhaustedBlockInteruptImproved() throws Exception {
    pool.setMaxActive(1);/* www.  ja v  a 2  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
    NonWaitingTestThread nwtt = new NonWaitingTestThread(pool);
    nwtt.start();
    // Give wtt time to start
    // Thread.sleep(200);
    nwtt.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
        if (nwtt._thrown instanceof InterruptedException) {
            fail("NoSuchElementException not expected");
        }

    }
    pool.returnObject(obj2);
    pool.close();
}