org.apache.commons.pool2.impl.GenericKeyedObjectPool Java Examples

The following examples show how to use org.apache.commons.pool2.impl.GenericKeyedObjectPool. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyedObjectPoolForTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Override
protected void doInitialize() throws Exception {

    if (this.pooledObjectFactory == null) {
        this.pooledObjectFactory = new ObjectFactory();
    }

    GenericKeyedObjectPool<String, Object> genericKeyedObjectPool = new GenericKeyedObjectPool<String, Object>(
            pooledObjectFactory, config);
    genericKeyedObjectPool.setTestOnBorrow(true);
    genericKeyedObjectPool.setTestOnCreate(true);
    genericKeyedObjectPool.setSoftMinEvictableIdleTimeMillis(DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
    genericKeyedObjectPool.setMinEvictableIdleTimeMillis(DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
    genericKeyedObjectPool.setTimeBetweenEvictionRunsMillis(DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
    this.objectPool = genericKeyedObjectPool;
}
 
Example #2
Source File: AbstractScripting.java    From cuba with Apache License 2.0 6 votes vote down vote up
private synchronized GenericKeyedObjectPool<String, Script> getPool() {
    if (pool == null) {
        GenericKeyedObjectPoolConfig<Script> poolConfig = new GenericKeyedObjectPoolConfig<>();
        poolConfig.setMaxTotalPerKey(-1);
        poolConfig.setMaxIdlePerKey(globalConfig.getGroovyEvaluationPoolMaxIdle());
        pool = new GenericKeyedObjectPool<>(
                new BaseKeyedPooledObjectFactory<String, Script>() {
                    @Override
                    public Script create(String key) {
                        return createScript(key);
                    }

                    @Override
                    public PooledObject<Script> wrap(Script value) {
                        return new DefaultPooledObject<>(value);
                    }
                },
                poolConfig
        );
    }
    return pool;
}
 
Example #3
Source File: KeyedObjectPoolForTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
public final void setKeyPooConfig(int minIdlePerKey, long softMinEvictableIdleTimeMillis, long minEvictableIdleTimeMillis, long timeBetweenEvictionRunsMillis) {

        if (objectPool instanceof GenericKeyedObjectPool) {
            logger.info("[setKeyPooConfig]{}, {}, {}, {}", minIdlePerKey, softMinEvictableIdleTimeMillis, minEvictableIdleTimeMillis, timeBetweenEvictionRunsMillis);
            GenericKeyedObjectPool genericKeyedObjectPool = (GenericKeyedObjectPool) objectPool;
            genericKeyedObjectPool.setMinIdlePerKey(minIdlePerKey);
            genericKeyedObjectPool.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
            genericKeyedObjectPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            genericKeyedObjectPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        } else {
            logger.warn("[setKeyPooConfig][not generickeyedobjectpool]");
        }
    }
 
Example #4
Source File: PooledContextSource.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new pooling context source, setting up the DirContext object
 * factory and generic keyed object pool.
 */
public PooledContextSource(PoolConfig poolConfig) {
	this.dirContextPooledObjectFactory = new DirContextPooledObjectFactory();
	if (poolConfig != null) {
		this.poolConfig = poolConfig;
		GenericKeyedObjectPoolConfig objectPoolConfig = getConfig(poolConfig);
		this.keyedObjectPool =
				new GenericKeyedObjectPool<Object,Object>(this.dirContextPooledObjectFactory, objectPoolConfig);
	} else  {
		this.keyedObjectPool =
				new GenericKeyedObjectPool<Object,Object>(this.dirContextPooledObjectFactory);
	}
}
 
Example #5
Source File: TestAbandonedBasicDataSource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * DBCP-180 - things get more interesting with statement pooling.
 */
@Test
public void testGarbageCollectorCleanUp02() throws Exception {
    ds.setPoolPreparedStatements(true);
    ds.setAccessToUnderlyingConnectionAllowed(true);
    final DelegatingConnection<?> conn = (DelegatingConnection<?>) ds.getConnection();
    final PoolableConnection poolableConn = (PoolableConnection) conn.getDelegate();
    final PoolingConnection poolingConn = (PoolingConnection) poolableConn.getDelegate();
    @SuppressWarnings("unchecked")
    final
    GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>  gkop =
            (GenericKeyedObjectPool<PStmtKey, DelegatingPreparedStatement>) TesterUtils.getField(poolingConn, "pstmtPool");
    Assertions.assertEquals(0, conn.getTrace().size());
    Assertions.assertEquals(0, gkop.getNumActive());
    createStatement(conn);
    Assertions.assertEquals(1, conn.getTrace().size());
    Assertions.assertEquals(1, gkop.getNumActive());
    System.gc();
    // Finalization happens in a separate thread. Give the test time for
    // that to complete.
    int count = 0;
    while (count < 50 && gkop.getNumActive() > 0) {
        Thread.sleep(100);
        count++;
    }
    Assertions.assertEquals(0, gkop.getNumActive());
    Assertions.assertEquals(0, conn.getTrace().size());
}
 
Example #6
Source File: TestPoolingConnection.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws Exception {
    con = new PoolingConnection(new TesterConnection("test", "test"));
    final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
    config.setMaxTotalPerKey(-1);
    config.setBlockWhenExhausted(false);
    config.setMaxWaitMillis(0);
    config.setMaxIdlePerKey(1);
    config.setMaxTotal(1);
    final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool =
            new GenericKeyedObjectPool<>(con, config);
    con.setStatementPool(stmtPool);
}
 
Example #7
Source File: TestKeyedCPDSConnectionFactory.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * JIRA: DBCP-442
 */
@Test
public void testNullValidationQuery() throws Exception {
    final UserPassKey key = new UserPassKey("userName", "password");
    final KeyedCPDSConnectionFactory factory =
            new KeyedCPDSConnectionFactory(cpds, null, -1, false);
    final GenericKeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool = new GenericKeyedObjectPool<>(factory);
    factory.setPool(pool);
    pool.setTestOnBorrow(true);
    final PooledConnection pcon = pool.borrowObject(key).getPooledConnection();
    final Connection con = pcon.getConnection();
    con.close();
}
 
Example #8
Source File: PoolableManagedConnectionFactory.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
/**
 * Uses the configured XAConnectionFactory to create a {@link PoolableManagedConnection}. Throws
 * <code>IllegalStateException</code> if the connection factory returns null. Also initializes the connection using
 * configured initialization SQL (if provided) and sets up a prepared statement pool associated with the
 * PoolableManagedConnection if statement pooling is enabled.
 */
@Override
public synchronized PooledObject<PoolableConnection> makeObject() throws Exception {
    Connection conn = getConnectionFactory().createConnection();
    if (conn == null) {
        throw new IllegalStateException("Connection factory returned null from createConnection");
    }
    initializeConnection(conn);
    if (getPoolStatements()) {
        conn = new PoolingConnection(conn);
        final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxTotalPerKey(-1);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(1);
        config.setMaxTotal(getMaxOpenPreparedStatements());
        final ObjectName dataSourceJmxName = getDataSourceJmxName();
        final long connIndex = getConnectionIndex().getAndIncrement();
        if (dataSourceJmxName != null) {
            final StringBuilder base = new StringBuilder(dataSourceJmxName.toString());
            base.append(Constants.JMX_CONNECTION_BASE_EXT);
            base.append(Long.toString(connIndex));
            config.setJmxNameBase(base.toString());
            config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
        } else {
            config.setJmxEnabled(false);
        }
        final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(
                (PoolingConnection) conn, config);
        ((PoolingConnection) conn).setStatementPool(stmtPool);
        ((PoolingConnection) conn).setCacheState(getCacheState());
    }
    final PoolableManagedConnection pmc = new PoolableManagedConnection(transactionRegistry, conn, getPool(),
            getDisconnectionSqlCodes(), isFastFailValidation());
    pmc.setCacheState(getCacheState());
    return new DefaultPooledObject<>(pmc);
}
 
Example #9
Source File: SharedPoolDataSource.java    From commons-dbcp with Apache License 2.0 5 votes vote down vote up
private void registerPool(final String userName, final String password) throws NamingException, SQLException {

        final ConnectionPoolDataSource cpds = testCPDS(userName, password);

        // Create an object pool to contain our PooledConnections
        factory = new KeyedCPDSConnectionFactory(cpds, getValidationQuery(), getValidationQueryTimeout(),
                isRollbackAfterValidation());
        factory.setMaxConnLifetimeMillis(getMaxConnLifetimeMillis());

        final GenericKeyedObjectPoolConfig<PooledConnectionAndInfo> config = new GenericKeyedObjectPoolConfig<>();
        config.setBlockWhenExhausted(getDefaultBlockWhenExhausted());
        config.setEvictionPolicyClassName(getDefaultEvictionPolicyClassName());
        config.setLifo(getDefaultLifo());
        config.setMaxIdlePerKey(getDefaultMaxIdle());
        config.setMaxTotal(getMaxTotal());
        config.setMaxTotalPerKey(getDefaultMaxTotal());
        config.setMaxWaitMillis(getDefaultMaxWaitMillis());
        config.setMinEvictableIdleTimeMillis(getDefaultMinEvictableIdleTimeMillis());
        config.setMinIdlePerKey(getDefaultMinIdle());
        config.setNumTestsPerEvictionRun(getDefaultNumTestsPerEvictionRun());
        config.setSoftMinEvictableIdleTimeMillis(getDefaultSoftMinEvictableIdleTimeMillis());
        config.setTestOnCreate(getDefaultTestOnCreate());
        config.setTestOnBorrow(getDefaultTestOnBorrow());
        config.setTestOnReturn(getDefaultTestOnReturn());
        config.setTestWhileIdle(getDefaultTestWhileIdle());
        config.setTimeBetweenEvictionRunsMillis(getDefaultTimeBetweenEvictionRunsMillis());

        final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> tmpPool = new GenericKeyedObjectPool<>(factory,
                config);
        factory.setPool(tmpPool);
        pool = tmpPool;
    }
 
Example #10
Source File: ModbusBinding.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private static void reconstructConnectionPool() {
    connectionFactory = new ModbusSlaveConnectionFactoryImpl();
    GenericKeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> genericKeyedObjectPool = new GenericKeyedObjectPool<>(
            connectionFactory, poolConfig);
    genericKeyedObjectPool.setSwallowedExceptionListener(new SwallowedExceptionListener() {

        @Override
        public void onSwallowException(Exception e) {
            logger.error("Connection pool swallowed unexpected exception: {}", e.getMessage());

        }
    });
    connectionPool = genericKeyedObjectPool;
}
 
Example #11
Source File: BaseTestProxiedKeyedObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    final GenericKeyedObjectPoolConfig<TestObject> config = new GenericKeyedObjectPoolConfig<>();
    config.setMaxTotal(3);

    final KeyedPooledObjectFactory<String, TestObject> factory =
            new TestKeyedObjectFactory();

    @SuppressWarnings("resource")
    final KeyedObjectPool<String, TestObject> innerPool =
            new GenericKeyedObjectPool<>(
                    factory, config);

    pool = new ProxiedKeyedObjectPool<>(innerPool, getproxySource());
}
 
Example #12
Source File: ObjectPoolIssue326.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
private List<Task> createTasks(final GenericKeyedObjectPool<Integer, Object> pool) {
    final List<Task> tasks = new ArrayList<>();
    for (int i = 0; i < 250; i++) {
        tasks.add(new Task(pool, i));
    }
    return tasks;
}
 
Example #13
Source File: QueryService.java    From kylin with Apache License 2.0 5 votes vote down vote up
private GenericKeyedObjectPool<PreparedContextKey, PreparedContext> createPreparedContextPool() {
    PreparedContextFactory factory = new PreparedContextFactory();
    KylinConfig kylinConfig = getConfig();
    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setMaxTotalPerKey(kylinConfig.getQueryMaxCacheStatementInstancePerKey());
    config.setMaxTotal(kylinConfig.getQueryMaxCacheStatementNum());
    config.setBlockWhenExhausted(false);
    config.setMinEvictableIdleTimeMillis(10 * 60 * 1000L); // cached statement will be evict if idle for 10 minutes
    config.setTimeBetweenEvictionRunsMillis(60 * 1000L); 
    GenericKeyedObjectPool<PreparedContextKey, PreparedContext> pool = new GenericKeyedObjectPool<>(factory,
            config);
    return pool;
}
 
Example #14
Source File: VMClientPool.java    From development with Apache License 2.0 5 votes vote down vote up
public void startPool() {
    pool = new GenericKeyedObjectPool<String, VMwareClient>(
            new VMClientFactory());
    ((GenericKeyedObjectPool<String, VMwareClient>) pool)
            .setMaxIdlePerKey(10);
    ((GenericKeyedObjectPool<String, VMwareClient>) pool).setMaxTotal(20);
    ((GenericKeyedObjectPool<String, VMwareClient>) pool)
            .setMaxTotalPerKey(20);
    ((GenericKeyedObjectPool<String, VMwareClient>) pool)
            .setTestOnBorrow(true);
}
 
Example #15
Source File: NodeManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void initConnectionPool() throws Exception {
    connPool = new GenericKeyedObjectPool<>(new CarreraConnectionFactory(config), config);
    for (Node node : getAllNodes()) {
        connPool.addObject(node);
    }
    initScheduler();
}
 
Example #16
Source File: QueryService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private GenericKeyedObjectPool<PreparedContextKey, PreparedContext> createPreparedContextPool() {
    PreparedContextFactory factory = new PreparedContextFactory();
    KylinConfig kylinConfig = getConfig();
    GenericKeyedObjectPoolConfig config = new GenericKeyedObjectPoolConfig();
    config.setMaxTotalPerKey(kylinConfig.getQueryMaxCacheStatementInstancePerKey());
    config.setMaxTotal(kylinConfig.getQueryMaxCacheStatementNum());
    config.setBlockWhenExhausted(false);
    config.setMinEvictableIdleTimeMillis(10 * 60 * 1000L); // cached statement will be evict if idle for 10 minutes
    config.setTimeBetweenEvictionRunsMillis(60 * 1000L); 
    GenericKeyedObjectPool<PreparedContextKey, PreparedContext> pool = new GenericKeyedObjectPool<>(factory,
            config);
    return pool;
}
 
Example #17
Source File: NodeManager.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
public void initConnectionPool() throws Exception {
    connPool = new GenericKeyedObjectPool<>(new CarreraConnectionFactory(config), config);
    for (Node node : getAllNodes()) {
        connPool.addObject(node);
    }
    initScheduler();
}
 
Example #18
Source File: CommonSshTestConfiguration.java    From jwala with Apache License 2.0 5 votes vote down vote up
public CommonSshTestConfiguration() throws JSchException {
    //TODO (Corey) generalize this so that %HOME% works
    //TODO create duplicate set of keys without a passphrase for testing
    builder = new JschBuilder(getKnownHostsFile(),
                              getPrivateKey());
    channelPool = new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(builder.build()));
    remoteSystemConnection = new RemoteSystemConnection("N9SFGLabTomcatAdmin",
                                                        /*"Passw0rd1"*/"===encryptMe===".toCharArray(),
                                                        "somehost0005",
                                                        22);
}
 
Example #19
Source File: CommonSshTestConfiguration.java    From jwala with Apache License 2.0 5 votes vote down vote up
public CommonSshTestConfiguration() throws JSchException {
    //TODO (Corey) generalize this so that %HOME% works
    //TODO create duplicate set of keys without a passphrase for testing
    builder = new JschBuilder(getKnownHostsFile(),
                              getPrivateKey());
    channelPool = new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(builder.build()));
    remoteSystemConnection = new RemoteSystemConnection("N9SFGLabTomcatAdmin",
                                                        /*"Passw0rd1"*/"===encryptedPassword===".toCharArray(),
                                                        "somehost0005",
                                                        22);
}
 
Example #20
Source File: AemServiceConfiguration.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Bean
public GenericKeyedObjectPool<ChannelSessionKey, Channel> getChannelPool(final SshConfig sshConfig) throws JSchException {
    final GenericKeyedObjectPoolConfig genericKeyedObjectPoolConfig = new GenericKeyedObjectPoolConfig();
    genericKeyedObjectPoolConfig.setMaxTotalPerKey(10);
    genericKeyedObjectPoolConfig.setBlockWhenExhausted(true);
    return new GenericKeyedObjectPool(new KeyedPooledJschChannelFactory(sshConfig.getJschBuilder().build()));
}
 
Example #21
Source File: CommonsObjectPool2MetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
private void createGenericKeyedObjectPool() {
    new GenericKeyedObjectPool<>(new BaseKeyedPooledObjectFactory<Object, Object>() {
        @Override
        public Object create(Object key) {
            return key;
        }

        @Override
        public PooledObject<Object> wrap(Object value) {
            return new DefaultPooledObject<>(value);
        }
    });
}
 
Example #22
Source File: TcpRpcEndpoint.java    From nutzcloud with Apache License 2.0 5 votes vote down vote up
public void init() {
    debug = conf.getBoolean("literpc.endpoint.tcp.debug", false);
    GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
    poolConfig.setMaxTotal(500);
    poolConfig.setTestWhileIdle(true);
    pool = new GenericKeyedObjectPool<>(new RpcSocketFactory(), poolConfig);
}
 
Example #23
Source File: ProductController.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/test/{productId}")
public Long test(@PathVariable final long productId) {

    productProducer.sendMessage(productId);

    Map<String,PooledConnectionFactory> pooledConnectionFactoryMap= ConnectionFactoryContainer.getAllPooledConnectionFactory();
    for(Map.Entry<String,PooledConnectionFactory> entry:pooledConnectionFactoryMap.entrySet()) {
        JimPooledConnectionFactory jimPooledConnectionFactory=(JimPooledConnectionFactory) entry.getValue();

        //jimPooledConnectionFactory.setExpiryTimeout();
        GenericKeyedObjectPool<ConnectionKey, ConnectionPool> jimConnectionsPool = ((JimPooledConnectionFactory) entry.getValue()).getJimConnectionsPool();

        //jimConnectionsPool.
        jimConnectionsPool.clearOldest();
        //jimConnectionsPool.set
        Map<String, List<DefaultPooledObjectInfo>> defStringListMap= jimConnectionsPool.listAllObjects();
        for(Map.Entry<String,List<DefaultPooledObjectInfo>> entry1 : defStringListMap.entrySet()){
            List<DefaultPooledObjectInfo> defaultPooledObjectInfos=entry1.getValue();
            System.out.println("123");
            for(DefaultPooledObjectInfo defaultPooledObjectInfo:defaultPooledObjectInfos){
                //defaultPooledObjectInfo.
                System.out.println("123");
                //((ConnectionPool)defaultPooledObjectInfo.pooledObject.getObject()).connection;
            }
        }
        //jimConnectionsPool.get
        System.out.println("123");

        //((ObjectDeque)((java.util.concurrent.ConcurrentHashMap.MapEntry)((java.util.concurrent.ConcurrentHashMap)jimConnectionsPool.poolMap).entrySet().toArray()[0]).getValue()).allObjects
    }

    return productId;
}
 
Example #24
Source File: ObjectPoolIssue326.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
Task(final GenericKeyedObjectPool<Integer, Object> pool, final int count) {
    m_pool = pool;
    m_key = count % 20;
}
 
Example #25
Source File: JmsPoolConnectionFactory.java    From pooled-jms with Apache License 2.0 4 votes vote down vote up
public void initConnectionsPool() {
    if (this.connectionsPool == null) {
        final GenericKeyedObjectPoolConfig<PooledConnection> poolConfig = new GenericKeyedObjectPoolConfig<>();
        poolConfig.setJmxEnabled(false);
        this.connectionsPool = new GenericKeyedObjectPool<PooledConnectionKey, PooledConnection>(
            new KeyedPooledObjectFactory<PooledConnectionKey, PooledConnection>() {
                @Override
                public PooledObject<PooledConnection> makeObject(PooledConnectionKey connectionKey) throws Exception {
                    Connection delegate = createProviderConnection(connectionKey);

                    PooledConnection connection = createPooledConnection(delegate);
                    connection.setIdleTimeout(getConnectionIdleTimeout());
                    connection.setMaxSessionsPerConnection(getMaxSessionsPerConnection());
                    connection.setBlockIfSessionPoolIsFull(isBlockIfSessionPoolIsFull());
                    if (isBlockIfSessionPoolIsFull() && getBlockIfSessionPoolIsFullTimeout() > 0) {
                        connection.setBlockIfSessionPoolIsFullTimeout(getBlockIfSessionPoolIsFullTimeout());
                    }
                    connection.setUseAnonymousProducers(isUseAnonymousProducers());
                    connection.setExplicitProducerCacheSize(getExplicitProducerCacheSize());

                    LOG.trace("Created new connection: {}", connection);

                    JmsPoolConnectionFactory.this.mostRecentlyCreated.set(connection);

                    return new DefaultPooledObject<PooledConnection>(connection);
                }

                @Override
                public void destroyObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
                    PooledConnection connection = pooledObject.getObject();
                    try {
                        LOG.trace("Destroying connection: {}", connection);
                        connection.close();
                    } catch (Exception e) {
                        LOG.warn("Close connection failed for connection: " + connection + ". This exception will be ignored.",e);
                    }
                }

                @Override
                public boolean validateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) {
                    PooledConnection connection = pooledObject.getObject();
                    if (connection != null && connection.expiredCheck()) {
                        LOG.trace("Connection has expired: {} and will be destroyed", connection);
                        return false;
                    }

                    return true;
                }

                @Override
                public void activateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
                }

                @Override
                public void passivateObject(PooledConnectionKey connectionKey, PooledObject<PooledConnection> pooledObject) throws Exception {
                }

            }, poolConfig);

        // Set max idle (not max active) since our connections always idle in the pool.
        this.connectionsPool.setMaxIdlePerKey(DEFAULT_MAX_CONNECTIONS);
        this.connectionsPool.setLifo(false);
        this.connectionsPool.setMinIdlePerKey(1);
        this.connectionsPool.setBlockWhenExhausted(false);

        // We always want our validate method to control when idle objects are evicted.
        this.connectionsPool.setTestOnBorrow(true);
        this.connectionsPool.setTestWhileIdle(true);
    }
}
 
Example #26
Source File: TestKeyedCPDSConnectionFactory.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
/**
 * JIRA DBCP-216
 *
 * Verify that pool counters are maintained properly and listeners are
 * cleaned up when a PooledConnection throws a connectionError event.
 */
@Test
public void testConnectionErrorCleanup() throws Exception {
    // Setup factory
    final UserPassKey key = new UserPassKey("userName", "password");
    final KeyedCPDSConnectionFactory factory =
        new KeyedCPDSConnectionFactory(cpds, null, -1, false);
    final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool = new GenericKeyedObjectPool<>(factory);
    factory.setPool(pool);

    // Checkout a pair of connections
    final PooledConnection pcon1 =
        pool.borrowObject(key)
            .getPooledConnection();
    final Connection con1 = pcon1.getConnection();
    final PooledConnection pcon2 =
        pool.borrowObject(key)
            .getPooledConnection();
    assertEquals(2, pool.getNumActive(key));
    assertEquals(0, pool.getNumIdle(key));

    // Verify listening
    final PooledConnectionProxy pc = (PooledConnectionProxy) pcon1;
    assertTrue(pc.getListeners().contains(factory));

    // Throw connectionError event
    pc.throwConnectionError();

    // Active count should be reduced by 1 and no idle increase
    assertEquals(1, pool.getNumActive(key));
    assertEquals(0, pool.getNumIdle(key));

    // Throw another one - we should be on cleanup list, so ignored
    pc.throwConnectionError();
    assertEquals(1, pool.getNumActive(key));
    assertEquals(0, pool.getNumIdle(key));

    // Ask for another connection - should trigger makeObject, which causes
    // cleanup, removing listeners.
    final PooledConnection pcon3 =
        pool.borrowObject(key)
            .getPooledConnection();
    assertTrue(!pcon3.equals(pcon1)); // better not get baddie back
    assertTrue(!pc.getListeners().contains(factory)); // verify cleanup
    assertEquals(2, pool.getNumActive(key));
    assertEquals(0, pool.getNumIdle(key));

    // Return good connections back to pool
    pcon2.getConnection().close();
    pcon3.getConnection().close();
    assertEquals(2, pool.getNumIdle(key));
    assertEquals(0, pool.getNumActive(key));

    // Verify pc is closed
    try {
       pc.getConnection();
       fail("Expecting SQLException using closed PooledConnection");
    } catch (final SQLException ex) {
        // expected
    }

    // Back from the dead - ignore the ghost!
    con1.close();
    assertEquals(2, pool.getNumIdle(key));
    assertEquals(0, pool.getNumActive(key));

    // Clear pool
    factory.getPool().clear();
    assertEquals(0, pool.getNumIdle(key));
}
 
Example #27
Source File: AbstractTransportPool.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
/**
 *  启动连接池
 *
 * @throws Exception
 */
public void start() throws Exception {
    LOG.info("Starting transport pool: " + poolConfig);
    this.pool = new GenericKeyedObjectPool<ServiceInstance<RpcPayload>, TTransport>(
            this, this.poolConfig);
}
 
Example #28
Source File: DriverAdapterCPDS.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
/**
 * Attempts to establish a database connection.
 *
 * @param pooledUserName
 *            name to be used for the connection
 * @param pooledUserPassword
 *            password to be used fur the connection
 */
@Override
public PooledConnection getPooledConnection(final String pooledUserName, final String pooledUserPassword)
        throws SQLException {
    getConnectionCalled = true;
    PooledConnectionImpl pooledConnection = null;
    // Workaround for buggy WebLogic 5.1 classloader - ignore the exception upon first invocation.
    try {
        if (connectionProperties != null) {
            update(connectionProperties, KEY_USER, pooledUserName);
            update(connectionProperties, KEY_PASSWORD, pooledUserPassword);
            pooledConnection = new PooledConnectionImpl(
                    DriverManager.getConnection(getUrl(), connectionProperties));
        } else {
            pooledConnection = new PooledConnectionImpl(
                    DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword));
        }
        pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    } catch (final ClassCircularityError e) {
        if (connectionProperties != null) {
            pooledConnection = new PooledConnectionImpl(
                    DriverManager.getConnection(getUrl(), connectionProperties));
        } else {
            pooledConnection = new PooledConnectionImpl(
                    DriverManager.getConnection(getUrl(), pooledUserName, pooledUserPassword));
        }
        pooledConnection.setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    }
    KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = null;
    if (isPoolPreparedStatements()) {
        final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
        config.setMaxTotalPerKey(Integer.MAX_VALUE);
        config.setBlockWhenExhausted(false);
        config.setMaxWaitMillis(0);
        config.setMaxIdlePerKey(getMaxIdle());
        if (getMaxPreparedStatements() <= 0) {
            // since there is no limit, create a prepared statement pool with an eviction thread;
            // evictor settings are the same as the connection pool settings.
            config.setTimeBetweenEvictionRunsMillis(getTimeBetweenEvictionRunsMillis());
            config.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun());
            config.setMinEvictableIdleTimeMillis(getMinEvictableIdleTimeMillis());
        } else {
            // since there is a limit, create a prepared statement pool without an eviction thread;
            // pool has LRU functionality so when the limit is reached, 15% of the pool is cleared.
            // see org.apache.commons.pool2.impl.GenericKeyedObjectPool.clearOldest method
            config.setMaxTotal(getMaxPreparedStatements());
            config.setTimeBetweenEvictionRunsMillis(-1);
            config.setNumTestsPerEvictionRun(0);
            config.setMinEvictableIdleTimeMillis(0);
        }
        stmtPool = new GenericKeyedObjectPool<>(pooledConnection, config);
        pooledConnection.setStatementPool(stmtPool);
    }
    return pooledConnection;
}
 
Example #29
Source File: TestKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Test
public void testKPOFReturnObjectUsages() throws Exception {
    final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
    final KeyedObjectPool<Object,Object> pool;
    try {
        pool = makeEmptyPool(factory);
    } catch(final UnsupportedOperationException uoe) {
        return; // test not supported
    }
    final List<MethodCall> expectedMethods = new ArrayList<>();
    Object obj;

    /// Test correct behavior code paths
    obj = pool.borrowObject(KEY);
    clear(factory, expectedMethods);

    // returned object should be passivated
    pool.returnObject(KEY, obj);
    expectedMethods.add(new MethodCall("passivateObject", KEY, obj));
    assertEquals(expectedMethods, factory.getMethodCalls());

    //// Test exception handling of returnObject
    reset(pool, factory, expectedMethods);

    // passivateObject should swallow exceptions and not add the object to the pool
    pool.addObject(KEY);
    pool.addObject(KEY);
    pool.addObject(KEY);
    assertEquals(3, pool.getNumIdle(KEY));
    obj = pool.borrowObject(KEY);
    obj = pool.borrowObject(KEY);
    assertEquals(1, pool.getNumIdle(KEY));
    assertEquals(2, pool.getNumActive(KEY));
    clear(factory, expectedMethods);
    factory.setPassivateObjectFail(true);
    pool.returnObject(KEY, obj);
    expectedMethods.add(new MethodCall("passivateObject", KEY, obj));
    TestObjectPool.removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
    assertEquals(expectedMethods, factory.getMethodCalls());
    assertEquals(1, pool.getNumIdle(KEY));   // Not added
    assertEquals(1, pool.getNumActive(KEY)); // But not active

    reset(pool, factory, expectedMethods);
    obj = pool.borrowObject(KEY);
    clear(factory, expectedMethods);
    factory.setPassivateObjectFail(true);
    factory.setDestroyObjectFail(true);
    try {
        pool.returnObject(KEY, obj);
        if (!(pool instanceof GenericKeyedObjectPool)) { // ugh, 1.3-compat
            fail("Expecting destroyObject exception to be propagated");
        }
    } catch (final PrivateException ex) {
        // Expected
    }
    pool.close();
}
 
Example #30
Source File: TestKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Test
public void testKPOFBorrowObjectUsages() throws Exception {
    final FailingKeyedPooledObjectFactory factory = new FailingKeyedPooledObjectFactory();
    final KeyedObjectPool<Object,Object> pool;
    try {
        pool = makeEmptyPool(factory);
    } catch(final UnsupportedOperationException uoe) {
        return; // test not supported
    }
    final List<MethodCall> expectedMethods = new ArrayList<>();
    Object obj;

    if (pool instanceof GenericKeyedObjectPool) {
        ((GenericKeyedObjectPool<Object,Object>) pool).setTestOnBorrow(true);
    }

    /// Test correct behavior code paths

    // existing idle object should be activated and validated
    pool.addObject(KEY);
    clear(factory, expectedMethods);
    obj = pool.borrowObject(KEY);
    expectedMethods.add(new MethodCall("activateObject", KEY, ZERO));
    expectedMethods.add(new MethodCall("validateObject", KEY, ZERO).returned(Boolean.TRUE));
    assertEquals(expectedMethods, factory.getMethodCalls());
    pool.returnObject(KEY, obj);

    //// Test exception handling of borrowObject
    reset(pool, factory, expectedMethods);

    // makeObject Exceptions should be propagated to client code from borrowObject
    factory.setMakeObjectFail(true);
    try {
        obj = pool.borrowObject(KEY);
        fail("Expected borrowObject to propagate makeObject exception.");
    } catch (final PrivateException pe) {
        // expected
    }
    expectedMethods.add(new MethodCall("makeObject", KEY));
    assertEquals(expectedMethods, factory.getMethodCalls());


    // when activateObject fails in borrowObject, a new object should be borrowed/created
    reset(pool, factory, expectedMethods);
    pool.addObject(KEY);
    clear(factory, expectedMethods);

    factory.setActivateObjectFail(true);
    expectedMethods.add(new MethodCall("activateObject", KEY, obj));
    try {
        pool.borrowObject(KEY);
        fail("Expecting NoSuchElementException");
    } catch (final NoSuchElementException e) {
        //Activate should fail
    }
    // After idle object fails validation, new on is created and activation
    // fails again for the new one.
    expectedMethods.add(new MethodCall("makeObject", KEY).returned(ONE));
    expectedMethods.add(new MethodCall("activateObject", KEY, ONE));
    TestObjectPool.removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
    assertEquals(expectedMethods, factory.getMethodCalls());

    // when validateObject fails in borrowObject, a new object should be borrowed/created
    reset(pool, factory, expectedMethods);
    pool.addObject(KEY);
    clear(factory, expectedMethods);

    factory.setValidateObjectFail(true);
    // testOnBorrow is on, so this will throw when the newly created instance
    // fails validation
    try {
        pool.borrowObject(KEY);
        fail("Expecting NoSuchElementException");
    } catch (final NoSuchElementException ex) {
        // expected
    }
    // Activate, then validate for idle instance
    expectedMethods.add(new MethodCall("activateObject", KEY, ZERO));
    expectedMethods.add(new MethodCall("validateObject", KEY, ZERO));
    // Make new instance, activate succeeds, validate fails
    expectedMethods.add(new MethodCall("makeObject", KEY).returned(ONE));
    expectedMethods.add(new MethodCall("activateObject", KEY, ONE));
    expectedMethods.add(new MethodCall("validateObject", KEY, ONE));
    TestObjectPool.removeDestroyObjectCall(factory.getMethodCalls());
    assertEquals(expectedMethods, factory.getMethodCalls());
    pool.close();
}