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

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

Introduction

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

Prototype

public GenericObjectPool(PooledObjectFactory<T> factory, GenericObjectPoolConfig config) 

Source Link

Document

Create a new GenericObjectPool using a specific configuration.

Usage

From source file:com.lambdaworks.redis.support.ConnectionPoolSupport.java

/**
 * Creates a new {@link GenericObjectPool} using the {@link Supplier}.
 *
 * @param connectionSupplier must not be {@literal null}.
 * @param config must not be {@literal null}.
 * @param wrapConnections {@literal false} to return direct connections that need to be returned to the pool using
 *        {@link ObjectPool#returnObject(Object)}. {@literal true} to return wrapped connection that are returned to the
 *        pool when invoking {@link StatefulConnection#close()}.
 * @param <T> connection type.//from  ww w. jav a  2s .  c om
 * @return the connection pool.
 */
@SuppressWarnings("unchecked")
public static <T extends StatefulConnection<?, ?>> GenericObjectPool<T> createGenericObjectPool(
        Supplier<T> connectionSupplier, GenericObjectPoolConfig config, boolean wrapConnections) {

    LettuceAssert.notNull(connectionSupplier, "Connection supplier must not be null");
    LettuceAssert.notNull(config, "GenericObjectPoolConfig must not be null");

    AtomicReference<ObjectPool<T>> poolRef = new AtomicReference<>();

    GenericObjectPool<T> pool = new GenericObjectPool<T>(new RedisPooledObjectFactory<>(connectionSupplier),
            config) {

        @Override
        public synchronized T borrowObject() throws Exception {
            return wrapConnections ? wrapConnection(super.borrowObject(), this) : super.borrowObject();
        }

        @Override
        public synchronized void returnObject(T obj) {

            if (wrapConnections && obj instanceof HasTargetConnection) {
                super.returnObject((T) ((HasTargetConnection) obj).getTargetConnection());
                return;
            }
            super.returnObject(obj);
        }
    };

    poolRef.set(pool);

    return pool;
}

From source file:ch.cyberduck.core.worker.ConcurrentTransferWorker.java

public ConcurrentTransferWorker(final ConnectionService connect, final Transfer transfer,
        final TransferOptions options, final TransferSpeedometer meter, final TransferPrompt prompt,
        final TransferErrorCallback error, final TransferItemCallback transferItemCallback,
        final ConnectionCallback connectionCallback, final ProgressListener progressListener,
        final StreamListener streamListener, final X509TrustManager trust, final X509KeyManager key,
        final PathCache cache, final Integer connections) {
    super(transfer, options, prompt, meter, error, transferItemCallback, progressListener, streamListener,
            connectionCallback);//w  w  w .  j  ava 2s .c o m
    final GenericObjectPoolConfig configuration = new GenericObjectPoolConfig() {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPoolConfig{");
            sb.append("connections=").append(connections);
            sb.append('}');
            return sb.toString();
        }
    };
    configuration.setJmxEnabled(false);
    configuration.setMinIdle(0);
    configuration.setMaxTotal(connections);
    configuration.setMaxIdle(connections);
    configuration.setBlockWhenExhausted(true);
    configuration.setMaxWaitMillis(BORROW_MAX_WAIT_INTERVAL);
    progress = progressListener;
    retry = Integer.max(PreferencesFactory.get().getInteger("connection.retry"), connections);
    pool = new GenericObjectPool<Session>(new SessionPool(connect, trust, key, cache, transfer.getHost()),
            configuration) {
        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("GenericObjectPool{");
            sb.append("configuration=").append(configuration);
            sb.append('}');
            return sb.toString();
        }
    };
    completion = new DefaultThreadPool<TransferStatus>(connections, "transfer");
}

From source file:gobblin.hive.HiveMetastoreClientPool.java

/**
 * Constructor for {@link HiveMetastoreClientPool}.
 * @deprecated It is recommended to use the static {@link #get} method instead. Use this constructor only if you
 *             different pool configurations are required.
 */// www.  j  a  v a  2  s.c o m
@Deprecated
public HiveMetastoreClientPool(Properties properties, Optional<String> metastoreURI) {
    this.hiveRegProps = new HiveRegProps(new State(properties));
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(this.hiveRegProps.getNumThreads());
    config.setMaxIdle(this.hiveRegProps.getNumThreads());

    this.factory = new HiveMetaStoreClientFactory(metastoreURI);
    this.pool = new GenericObjectPool<>(this.factory, config);
    this.hiveConf = this.factory.getHiveConf();
}

From source file:com.threecrickets.prudence.cache.SqlCache.java

/**
 * Constructor.//from ww  w  . ja va  2 s .  co  m
 * 
 * @param dataSource
 *        The data source
 * @param maxSize
 *        The max entry count
 * @param poolSize
 *        The number of connections in the pool
 * @param lockSource
 *        The lock source
 */
public SqlCache(DataSource dataSource, int maxSize, int poolSize, LockSource lockSource) {
    this.maxSize = maxSize;
    this.lockSource = lockSource;

    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    config.setMaxTotal(poolSize);
    config.setMaxIdle(poolSize);
    config.setMinIdle(poolSize);
    DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource);
    PoolableConnectionFactory pooledObjectFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPool<PoolableConnection> pool = new GenericObjectPool<PoolableConnection>(pooledObjectFactory,
            config);
    pooledObjectFactory.setPool(pool);
    this.dataSource = new PoolingDataSource<PoolableConnection>(pool);
}

From source file:com.streamsets.pipeline.stage.origin.ipctokafka.IpcToKafkaServlet.java

@Override
public void init() throws ServletException {
    super.init();
    int max = configs.maxConcurrentRequests;
    int minIdle = Math.max(1, configs.maxConcurrentRequests / 4);
    int maxIdle = configs.maxConcurrentRequests / 2;
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxTotal(max);//ww  w  .j  a  v  a 2s.c  om
    poolConfig.setMinIdle(minIdle);
    poolConfig.setMaxIdle(maxIdle);
    LOG.debug("Creating Kafka producer pool with max '{}' minIdle '{}' maxIdle '{}'", max, minIdle, maxIdle);
    kafkaProducerPool = new GenericObjectPool<>(
            new SdcKafkaProducerPooledObjectFactory(kafkaConfigBean.kafkaConfig, DataFormat.SDC_JSON),
            poolConfig);
}

From source file:com.streamsets.pipeline.stage.origin.udptokafka.KafkaUDPConsumer.java

public void init() {
    executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(udpConfigBean.concurrency);
    int max = udpConfigBean.concurrency;
    int minIdle = Math.max(1, udpConfigBean.concurrency / 4);
    int maxIdle = udpConfigBean.concurrency / 2;
    GenericObjectPoolConfig kakfaPoolConfig = new GenericObjectPoolConfig();
    kakfaPoolConfig.setMaxTotal(udpConfigBean.concurrency);
    kakfaPoolConfig.setMinIdle(minIdle);
    kakfaPoolConfig.setMaxIdle(maxIdle);
    LOG.debug("Creating Kafka producer pool with max '{}' minIdle '{}' maxIdle '{}'", max, minIdle, maxIdle);
    kafkaProducerPool = new GenericObjectPool<>(
            new SdcKafkaProducerPooledObjectFactory(kafkaTargetConfig, DataFormat.BINARY), kakfaPoolConfig);
    GenericObjectPoolConfig serializerPoolConfig = new GenericObjectPoolConfig();
    serializerPoolConfig.setMaxTotal(udpConfigBean.concurrency);
    serializerPoolConfig.setMinIdle(udpConfigBean.concurrency);
    serializerPoolConfig.setMaxIdle(udpConfigBean.concurrency);
    udpSerializerPool = new GenericObjectPool<>(new UDPMessageSerializerPooledObjectFactory(),
            serializerPoolConfig);//from  ww w .  j a v  a  2 s  . c  o  m
    udpType = UDP_DATA_FORMAT_MAP.get(udpConfigBean.dataFormat);
    LOG.debug("Started, concurrency '{}'", udpConfigBean.concurrency);
}

From source file:com.axibase.tsd.client.HttpClientManager.java

private GenericObjectPool<HttpClient> createObjectPool() {
    GenericObjectPool<HttpClient> httpClientGenericObjectPool = objectPoolAtomicReference.get();
    if (httpClientGenericObjectPool == null) {
        httpClientGenericObjectPool = new GenericObjectPool<HttpClient>(new HttpClientBasePooledObjectFactory(),
                objectPoolConfig);// ww w  . j  a  va  2  s . co m
        objectPoolAtomicReference.compareAndSet(null, httpClientGenericObjectPool);
    }
    return objectPoolAtomicReference.get();
}

From source file:herddb.jdbc.BasicHerdDBDataSource.java

protected synchronized void ensureClient() throws SQLException {
    if (client == null) {
        ClientConfiguration clientConfiguration = new ClientConfiguration(properties);
        Properties propsNoPassword = new Properties(properties);
        if (propsNoPassword.contains("password")) {
            propsNoPassword.setProperty("password", "-------");
        }/*from   www. j  a v a 2s .c  o m*/
        LOGGER.log(Level.INFO, "Booting HerdDB Client, url:" + url + ", properties:" + propsNoPassword
                + " clientConfig " + clientConfiguration);
        clientConfiguration.readJdbcUrl(url);
        if (properties.containsKey("discoverTableSpaceFromQuery")) {
            this.discoverTableSpaceFromQuery = clientConfiguration.getBoolean("discoverTableSpaceFromQuery",
                    true);
        }
        client = new HDBClient(clientConfiguration);
    }
    if (pool == null) {
        if (properties.containsKey("maxActive")) {
            this.maxActive = Integer.parseInt(properties.get("maxActive").toString());
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setBlockWhenExhausted(true);
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxActive);
        config.setMinIdle(maxActive / 2);
        config.setJmxNamePrefix("HerdDBClient");
        pool = new GenericObjectPool<>(new ConnectionsFactory(), config);
    }
}

From source file:com.yahoo.athenz.common.server.db.DataSourceFactory.java

static PoolableDataSource create(ConnectionFactory connectionFactory) {

    // setup our pool config object

    GenericObjectPoolConfig config = setupPoolConfig();

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            null);/*from  w  w  w . j a v a  2  s.co m*/

    // Set max lifetime of a connection in milli-secs, after which it will
    // always fail activation, passivation, and validation.
    // Value of -1 means infinite life time. The default value
    // defined in this class is 10 minutes.
    long connTtlMillis = retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TTL, MAX_TTL_CONN_MS);
    poolableConnectionFactory.setMaxConnLifetimeMillis(connTtlMillis);
    if (LOG.isInfoEnabled()) {
        LOG.info("Setting Time-To-Live interval for live connections (" + connTtlMillis + ") milli-secs");
    }

    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    poolableConnectionFactory.setPool(connectionPool);

    AthenzDataSource dataSource = new AthenzDataSource(connectionPool);
    return dataSource;
}

From source file:com.mirth.connect.connectors.file.FileConnector.java

/**
 * Gets the pool of connections to the "server" for the specified endpoint, creating the pool if
 * necessary.//from w ww . j a v  a 2 s.  co  m
 * 
 * @param uri
 *            The URI of the endpoint the created pool should be associated with.
 * @param message
 *            ???
 * @return The pool of connections for this endpoint.
 */
private synchronized ObjectPool<FileSystemConnection> getConnectionPool(
        FileSystemConnectionOptions fileSystemOptions) throws Exception {
    FileSystemConnectionFactory fileSystemConnectionFactory = getFileSystemConnectionFactory(fileSystemOptions);
    String key = fileSystemConnectionFactory.getPoolKey();
    ObjectPool<FileSystemConnection> pool = pools.get(key);

    if (pool == null) {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        if (isValidateConnection()) {
            config.setTestOnBorrow(true);
            config.setTestOnReturn(true);
        }
        pool = new GenericObjectPool<FileSystemConnection>(fileSystemConnectionFactory, config);

        pools.put(key, pool);
    }
    return pool;
}