org.apache.commons.pool2.KeyedObjectPool Java Examples

The following examples show how to use org.apache.commons.pool2.KeyedObjectPool. 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: AbstractPoolTestCase.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    contextMock = mock(Context.class);
    dirContextMock = mock(DirContext.class);
    ldapContextMock = mock(LdapContext.class);
    keyedObjectPoolMock = mock(KeyedObjectPool.class);
    contextSourceMock = mock(ContextSource.class);
    dirContextValidatorMock = mock(DirContextValidator.class);
}
 
Example #2
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
public TestThread(final KeyedObjectPool<String,T> pool, final int iter, final int startDelay,
    final int holdTime, final boolean randomDelay, final T expectedObject, final String key) {
    _pool = pool;
    _iter = iter;
    _startDelay = startDelay;
    _holdTime = holdTime;
    _randomDelay = randomDelay;
    _expectedObject = expectedObject;
    _key = key;

}
 
Example #3
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 #4
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 #5
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 #6
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
@Override
protected KeyedObjectPool<Object,Object> makeEmptyPool(final int minCapacity) {
    final KeyedPooledObjectFactory<Object,Object> perKeyFactory =
            new SimplePerKeyFactory();
    final GenericKeyedObjectPool<Object,Object> perKeyPool =
        new GenericKeyedObjectPool<>(perKeyFactory);
    perKeyPool.setMaxTotalPerKey(minCapacity);
    perKeyPool.setMaxIdlePerKey(minCapacity);
    return perKeyPool;
}
 
Example #7
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 #8
Source File: DelegatingContext.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new delegating context for the specified pool, context and context type.
 *
 * @param keyedObjectPool The pool the delegate context was checked out from.
 * @param delegateContext The context to delegate operations to.
 * @param dirContextType The type of context, used as a key for the pool.
 * @throws IllegalArgumentException if any of the arguments are null
 */
public DelegatingContext(KeyedObjectPool<Object,Object> keyedObjectPool, Context delegateContext, DirContextType dirContextType) {
    Assert.notNull(keyedObjectPool, "keyedObjectPool may not be null");
    Assert.notNull(delegateContext, "delegateContext may not be null");
    Assert.notNull(dirContextType, "dirContextType may not be null");

    this.keyedObjectPool = keyedObjectPool;
    this.delegateContext = delegateContext;
    this.dirContextType = dirContextType;
}
 
Example #9
Source File: PoolConfiguration.java    From spring-thrift-starter with MIT License 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "thriftClientsPool")
public KeyedObjectPool<ThriftClientKey, TServiceClient> thriftClientsPool() {
    GenericKeyedObjectPoolConfig poolConfig = new GenericKeyedObjectPoolConfig();
    poolConfig.setMaxTotal(maxTotalThreads);
    poolConfig.setMaxIdlePerKey(maxIdleThreads);
    poolConfig.setMaxTotalPerKey(maxThreads);
    poolConfig.setJmxEnabled(false); //cause spring will autodetect itself
    return new ThriftClientPool(thriftClientPoolFactory(), poolConfig);
}
 
Example #10
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 #11
Source File: KeyedCPDSConnectionFactory.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
public void setPool(final KeyedObjectPool<UserPassKey, PooledConnectionAndInfo> pool) {
    this.pool = pool;
}
 
Example #12
Source File: PooledConnectionImpl.java    From commons-dbcp with Apache License 2.0 4 votes vote down vote up
public void setStatementPool(final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> statementPool) {
    pStmtPool = statementPool;
}
 
Example #13
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 #14
Source File: ModbusSerialSlave.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public ModbusSerialSlave(String slave, KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool) {
    super(slave, connectionPool);
    transaction = new ModbusSerialTransaction();
    endpoint = new ModbusSerialSlaveEndpoint(serialParameters);
}
 
Example #15
Source File: ModbusTcpSlave.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public ModbusTcpSlave(String slave, KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool) {
    super(slave, connectionPool);
    transaction = new ModbusTCPTransaction();
    ((ModbusTCPTransaction) transaction).setReconnecting(false);
}
 
Example #16
Source File: JmsPoolSession.java    From pooled-jms with Apache License 2.0 4 votes vote down vote up
public JmsPoolSession(PooledSessionKey key, PooledSessionHolder sessionHolder, KeyedObjectPool<PooledSessionKey, PooledSessionHolder> sessionPool, boolean transactional) {
    this.key = key;
    this.sessionHolder = sessionHolder;
    this.sessionPool = sessionPool;
    this.transactional = transactional;
}
 
Example #17
Source File: ModbusBinding.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * For testing
 */
static KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> getReconstructedConnectionPoolForTesting() {
    reconstructConnectionPool();
    return connectionPool;
}
 
Example #18
Source File: ModbusIPSlave.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public ModbusIPSlave(String slave, KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool) {
    super(slave, connectionPool);
    updateEndpoint();
}
 
Example #19
Source File: VMClientPool.java    From development with Apache License 2.0 4 votes vote down vote up
public KeyedObjectPool<String, VMwareClient> getPool() {
    return pool;
}
 
Example #20
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Override
protected KeyedObjectPool<Object,Object> makeEmptyPool(final KeyedPooledObjectFactory<Object,Object> fac) {
    return new GenericKeyedObjectPool<>(fac);
}
 
Example #21
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public InvalidateThread(final KeyedObjectPool<String, String> pool, final String key, final String obj) {
    this.obj = obj;
    this.pool = pool;
    this.key = key;
}
 
Example #22
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public SimpleTestThread(final KeyedObjectPool<String,T> pool, final String key) {
    _pool = pool;
    _key = key;
}
 
Example #23
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public WaitingTestThread(final KeyedObjectPool<String,String> pool, final String key, final long pause) {
    _pool = pool;
    _key = key;
    _pause = pause;
    _thrown = null;
}
 
Example #24
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public TestThread(final KeyedObjectPool<String,T> pool) {
    this(pool, 100, 50, 50, true, null, null);
}
 
Example #25
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public TestThread(final KeyedObjectPool<String,T> pool, final int iter) {
    this(pool, iter, 50, 50, true, null, null);
}
 
Example #26
Source File: TestGenericKeyedObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
public TestThread(final KeyedObjectPool<String,T> pool, final int iter, final int delay) {
    this(pool, iter, delay, delay, true, null, null);
}
 
Example #27
Source File: ModbusUdpSlave.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
public ModbusUdpSlave(String slave, KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool) {
    super(slave, connectionPool);
    transaction = new ModbusUDPTransaction();
}
 
Example #28
Source File: ModbusSlave.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @param slave slave name from cfg file used for item binding
 * @connectionPool pool to create connections
 */
public ModbusSlave(String slave, KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> connectionPool) {
    this.name = slave;
    this.connectionPool = connectionPool;
}
 
Example #29
Source File: PoolableCallableStatement.java    From commons-dbcp with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor.
 *
 * @param callableStatement
 *            the underlying {@link CallableStatement}
 * @param key
 *            the key for this statement in the {@link KeyedObjectPool}
 * @param pool
 *            the {@link KeyedObjectPool} from which this CallableStatement was obtained
 * @param connection
 *            the {@link DelegatingConnection} that created this CallableStatement
 */
public PoolableCallableStatement(final CallableStatement callableStatement, final PStmtKey key,
        final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> pool,
        final DelegatingConnection<Connection> connection) {
    super(connection, callableStatement);
    this.pool = pool;
    this.key = key;

    // Remove from trace now because this statement will be
    // added by the activate method.
    removeThisTrace(getConnectionInternal());
}
 
Example #30
Source File: PoolablePreparedStatement.java    From commons-dbcp with Apache License 2.0 3 votes vote down vote up
/**
 * Constructor.
 *
 * @param stmt
 *            my underlying {@link PreparedStatement}
 * @param key
 *            my key" as used by {@link KeyedObjectPool}
 * @param pool
 *            the {@link KeyedObjectPool} from which I was obtained.
 * @param conn
 *            the {@link java.sql.Connection Connection} from which I was created
 */
public PoolablePreparedStatement(final PreparedStatement stmt, final K key,
        final KeyedObjectPool<K, PoolablePreparedStatement<K>> pool, final DelegatingConnection<?> conn) {
    super(conn, stmt);
    this.pool = pool;
    this.key = key;

    // Remove from trace now because this statement will be
    // added by the activate method.
    removeThisTrace(getConnectionInternal());
}