Example usage for org.apache.commons.pool2.impl GenericObjectPool borrowObject

List of usage examples for org.apache.commons.pool2.impl GenericObjectPool borrowObject

Introduction

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

Prototype

@Override
public T borrowObject() throws Exception 

Source Link

Document

Equivalent to #borrowObject(long) borrowObject ( #getMaxWaitMillis() ).

Usage

From source file:io.lettuce.core.support.ConnectionPoolSupportTest.java

@Test
public void wrappedMasterSlaveConnectionShouldUseWrappers() throws Exception {

    GenericObjectPool<StatefulRedisMasterSlaveConnection<String, String>> pool = ConnectionPoolSupport
            .createGenericObjectPool(//from  ww  w .  j a  v a2  s.c o m
                    () -> MasterSlave.connect(client, new StringCodec(), RedisURI.create(host, port)),
                    new GenericObjectPoolConfig());

    StatefulRedisMasterSlaveConnection<String, String> connection = pool.borrowObject();
    RedisCommands<String, String> sync = connection.sync();

    assertThat(connection).isInstanceOf(StatefulRedisMasterSlaveConnection.class);
    assertThat(Proxy.isProxyClass(connection.getClass())).isTrue();

    assertThat(sync).isInstanceOf(RedisCommands.class);
    assertThat(connection.async()).isInstanceOf(RedisAsyncCommands.class)
            .isNotInstanceOf(RedisAsyncCommandsImpl.class);
    assertThat(connection.reactive()).isInstanceOf(RedisReactiveCommands.class)
            .isNotInstanceOf(RedisReactiveCommandsImpl.class);
    assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisConnection.class)
            .isNotInstanceOf(StatefulRedisConnectionImpl.class).isSameAs(connection);

    connection.close();
    pool.close();
}

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

public void warmup(final GenericObjectPool<Worker> objectPool) throws CoreException {
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {/*w  w w.ja  v  a 2s  . c  o m*/
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());
    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:com.adaptris.core.services.splitter.ServiceWorkerPool.java

/**
 * /*from ww w .ja  v  a  2s  .  c  o m*/
 * @deprecated since 3.8.3 switch to commons-pool2 instead.
 */
@Deprecated
@Removal(version = "3.9.0", message = "use commons-pool2 variant instead")
public void warmup(final org.apache.commons.pool.impl.GenericObjectPool<Worker> objectPool)
        throws CoreException {
    logDeprecationWarning();
    ExecutorService populator = Executors
            .newCachedThreadPool(new ManagedThreadFactory(this.getClass().getSimpleName()));
    try {
        log.trace("Warming up {} service-workers", maxThreads);
        final List<Future<Worker>> futures = new ArrayList<>(maxThreads);

        for (int i = 0; i < maxThreads; i++) {
            futures.add(populator.submit(new Callable<Worker>() {

                @Override
                public Worker call() throws Exception {
                    return objectPool.borrowObject();
                }

            }));
        }
        for (Worker w : waitFor(futures)) {
            objectPool.returnObject(w);
        }
        log.trace("ObjectPool contains {} (active) of {} objects", objectPool.getNumActive(),
                objectPool.getNumIdle());

    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    } finally {
        populator.shutdownNow();
    }
}

From source file:org.apache.omid.tso.BatchPoolModule.java

@Provides
@Singleton//from  w w  w  .  ja v a2  s .  co  m
ObjectPool<Batch> getBatchPool() throws Exception {

    int poolSize = config.getNumConcurrentCTWriters();
    int batchSize = config.getBatchSizePerCTWriter();

    LOG.info("Pool Size (# of Batches) {}; Batch Size {}", poolSize, batchSize);
    LOG.info("Total Batch Size (Pool size * Batch Size): {}", poolSize * batchSize);
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(poolSize);
    config.setBlockWhenExhausted(true);
    GenericObjectPool<Batch> batchPool = new GenericObjectPool<>(new Batch.BatchFactory(batchSize), config);
    LOG.info("Pre-creating objects in the pool..."); // TODO There should be a better way to do this
    List<Batch> batches = new ArrayList<>(poolSize);
    for (int i = 0; i < poolSize; i++) {
        batches.add(batchPool.borrowObject());
    }
    for (Batch batch : batches) {
        batchPool.returnObject(batch);
    }
    return batchPool;

}

From source file:org.moneta.healthcheck.DbcpConnectionPoolHealthCheck.java

@Override
protected Result check() throws Exception {

    GenericObjectPool<PoolableConnection> pool = (GenericObjectPool<PoolableConnection>) connectionPool;
    if (pool.getNumWaiters() > maxWaitingConnections) {
        return Result.unhealthy(
                "Overloaded connection pool.  name=" + poolName + " nbrWaiters=" + pool.getNumWaiters());
    }//w  w  w  .  j av  a 2 s.  co  m

    PoolableConnectionFactory poolFactory = (PoolableConnectionFactory) pool.getFactory();
    PoolableConnection conn = null;
    try {
        conn = pool.borrowObject();
        poolFactory.validateConnection(conn);
    } catch (Exception e) {
        return Result
                .unhealthy("Database connection validation error.  error=" + ExceptionUtils.getStackTrace(e));
    } finally {
        DbUtils.closeQuietly(conn);
    }

    return Result.healthy();
}

From source file:org.springframework.data.redis.connection.lettuce.LettucePoolingConnectionProvider.java

@Override
public <T extends StatefulConnection<?, ?>> T getConnection(Class<T> connectionType) {

    GenericObjectPool<StatefulConnection<?, ?>> pool = pools.computeIfAbsent(connectionType, poolType -> {
        return ConnectionPoolSupport.createGenericObjectPool(
                () -> connectionProvider.getConnection(connectionType), poolConfig, false);
    });//from   w  ww . ja  v a 2 s.co  m

    try {

        StatefulConnection<?, ?> connection = pool.borrowObject();

        poolRef.put(connection, pool);

        return connectionType.cast(connection);
    } catch (Exception e) {
        throw new PoolException("Could not get a resource from the pool", e);
    }
}