Java Code Examples for org.apache.commons.pool2.ObjectPool#borrowObject()

The following examples show how to use org.apache.commons.pool2.ObjectPool#borrowObject() . 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: TestBatchPool.java    From phoenix-omid with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 10_000)
public void testBatchPoolInitializesAllBatchObjectsAsIdle() throws Exception {

    final ObjectPool<Batch> batchPool = injector.getInstance(Key.get(new TypeLiteral<ObjectPool<Batch>>() {}));

    assertEquals(batchPool.getNumActive(), 0);
    assertEquals(batchPool.getNumIdle(), CONCURRENT_WRITERS);

    // Now make all of them active and check it below
    for (int i = 0; i < CONCURRENT_WRITERS; i++) {
        batchPool.borrowObject();
    }

    assertEquals(batchPool.getNumActive(), CONCURRENT_WRITERS);
    assertEquals(batchPool.getNumIdle(), 0);

}
 
Example 2
Source File: MonetaConfiguration.java    From moneta with Apache License 2.0 6 votes vote down vote up
/**
 * Will return a dbConnection for a given information topic.
 * @param sourceName Data source name
 * @return topicDbConnection connection topic
 */
public Connection getConnection(String sourceName) {
	Validate.notEmpty(sourceName, "Null or blank sourceName not allowed");
	Validate.isTrue(this.initRun, "Moneta not properly initialized.");
	
	ObjectPool connectionPool = connectionPoolMap.get(sourceName);
	if (connectionPool == null) {
		throw new MonetaException("Data Source Not Found")
			.addContextValue("sourceName", sourceName);
	}
	
	try {
		return (Connection)connectionPool.borrowObject();
	} catch (Exception e) {
		throw new MonetaException("Error creating JDBC connection")
			.addContextValue("sourceName", sourceName);
	}
}
 
Example 3
Source File: PersistenceProcessorImpl.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Inject
PersistenceProcessorImpl(TSOServerConfig config,
                         @Named("PersistenceStrategy") WaitStrategy strategy,
                         CommitTable commitTable,
                         ObjectPool<Batch> batchPool,
                         Panicker panicker,
                         PersistenceProcessorHandler[] handlers,
                         MetricsRegistry metrics)
        throws Exception {

    // ------------------------------------------------------------------------------------------------------------
    // Disruptor initialization
    // ------------------------------------------------------------------------------------------------------------

    ThreadFactoryBuilder threadFactory = new ThreadFactoryBuilder().setNameFormat("persist-%d");
    this.disruptorExec = Executors.newFixedThreadPool(config.getNumConcurrentCTWriters(), threadFactory.build());

    this.disruptor = new Disruptor<>(EVENT_FACTORY, 1 << 20, disruptorExec , SINGLE, strategy);
    disruptor.handleExceptionsWith(new FatalExceptionHandler(panicker)); // This must be before handleEventsWith()
    disruptor.handleEventsWithWorkerPool(handlers);
    this.persistRing = disruptor.start();

    // ------------------------------------------------------------------------------------------------------------
    // Attribute initialization
    // ------------------------------------------------------------------------------------------------------------

    this.metrics = metrics;
    this.batchSequence = 0L;
    this.batchPool = batchPool;
    this.currentBatch = batchPool.borrowObject();

    LOG.info("PersistentProcessor initialized");
}
 
Example 4
Source File: TestBatchPool.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 10_000)
public void testBatchPoolBlocksWhenAllObjectsAreActive() throws Exception {

    ExecutorService executor = Executors.newCachedThreadPool();

    final ObjectPool<Batch> batchPool = injector.getInstance(Key.get(new TypeLiteral<ObjectPool<Batch>>() {}));

    // Try to get one more batch than the number of concurrent writers set
    for (int i = 0; i < CONCURRENT_WRITERS + 1; i++) {

        // Wrap the call to batchPool.borrowObject() in a task to detect when is blocked by the ObjectPool
        Callable<Batch> task = new Callable<Batch>() {
            public Batch call() throws Exception {
                return batchPool.borrowObject();
            }
        };

        Future<Batch> future = executor.submit(task);

        try {
            /** The future below should return immediately except for the last one, which should be blocked by
                the ObjectPool as per the configuration setup in the {@link BatchPoolModule} */
            Batch batch = future.get(1, TimeUnit.SECONDS);
            LOG.info("Batch {} returned with success", batch.toString());
        } catch (TimeoutException ex) {
            if (i < CONCURRENT_WRITERS) {
                fail();
            } else {
                LOG.info("Yaaaayyyyy! This is the blocked call!");
            }
        } finally {
            future.cancel(true); // may or may not desire this
        }

    }

}
 
Example 5
Source File: ConsumerProxy.java    From ourea with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    int remainRetryTimes = clientConfig.getRetryTimes();
    String exceptionMsg = null;

    do {

        ObjectPool<TTransport> connPool = null;
        TTransport transport = null;
        InvokeConn conn = null;
        try {
            Invocation invocation = new Invocation(serviceInfo.getInterfaceClazz().getName(), method.getName());
            conn = clientConfig.getLoadBalanceStrategy().select(PROVIDER_CONN_LIST, invocation);
            connPool = conn.getConnPool();
            transport = connPool.borrowObject();
            TProtocol protocol = new TBinaryProtocol(transport);
            TServiceClient client = serviceClientConstructor.newInstance(protocol);

            return method.invoke(client, args);
        } catch (Exception e) {
            // 服务多次重试连接不上,则直接将该服务对应信息移除
            if (e instanceof OureaConnCreateException) {
                if (PROVIDER_CONN_LIST.remove(conn) && conn != null && conn.getConnPool() != null){
                    conn.getConnPool().close();
                    conn = null;//help GC
                }
            }
            LOGGER.warn("invoke thrift rpc provider fail.e:", e);
            exceptionMsg = e.getMessage();
        } finally {
            if (connPool != null && transport != null) {
                connPool.invalidateObject(transport);
            }
        }
    } while (remainRetryTimes-- > 0);

    throw new OureaException("invoke fail.msg:" + exceptionMsg);
}
 
Example 6
Source File: ConnectionPoolFactoryTest.java    From moneta with Apache License 2.0 5 votes vote down vote up
@Test
public void testBasicHappyPath() throws Exception {
	ObjectPool<PoolableConnection> pool = ConnectionPoolFactory.createConnectionPool(dataSource);
	Assert.assertTrue(pool != null);
	
	Connection conn = pool.borrowObject();
	Assert.assertTrue(conn != null);
	Assert.assertTrue(!conn.isClosed() );
}
 
Example 7
Source File: TestObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
@Test
public void testPOFInvalidateObjectUsages() throws Exception {
    final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
    final ObjectPool<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();
    clear(factory, expectedMethods);

    // invalidated object should be destroyed
    pool.invalidateObject(obj);
    expectedMethods.add(new MethodCall("destroyObject", obj));
    assertEquals(expectedMethods, factory.getMethodCalls());

    //// Test exception handling of invalidateObject
    reset(pool, factory, expectedMethods);
    obj = pool.borrowObject();
    clear(factory, expectedMethods);
    factory.setDestroyObjectFail(true);
    try {
        pool.invalidateObject(obj);
        fail("Expecting destroy exception to propagate");
    } catch (final PrivateException ex) {
        // Expected
    }
    Thread.sleep(250); // could be deferred
    removeDestroyObjectCall(factory.getMethodCalls());
    assertEquals(expectedMethods, factory.getMethodCalls());
    pool.close();
}
 
Example 8
Source File: TestObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Test
public void testPOFReturnObjectUsages() throws Exception {
    final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
    final ObjectPool<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();
    clear(factory, expectedMethods);

    // returned object should be passivated
    pool.returnObject(obj);
    // StackObjectPool, SoftReferenceObjectPool also validate on return
    if (pool instanceof SoftReferenceObjectPool) {
        expectedMethods.add(new MethodCall(
                "validateObject", obj).returned(Boolean.TRUE));
    }
    expectedMethods.add(new MethodCall("passivateObject", obj));
    assertEquals(expectedMethods, factory.getMethodCalls());

    //// Test exception handling of returnObject
    reset(pool, factory, expectedMethods);
    pool.addObject();
    pool.addObject();
    pool.addObject();
    assertEquals(3, pool.getNumIdle());
    // passivateObject should swallow exceptions and not add the object to the pool
    obj = pool.borrowObject();
    pool.borrowObject();
    assertEquals(1, pool.getNumIdle());
    assertEquals(2, pool.getNumActive());
    clear(factory, expectedMethods);
    factory.setPassivateObjectFail(true);
    pool.returnObject(obj);
    // StackObjectPool, SoftReferenceObjectPool also validate on return
    if (pool instanceof SoftReferenceObjectPool) {
        expectedMethods.add(new MethodCall(
                "validateObject", obj).returned(Boolean.TRUE));
    }
    expectedMethods.add(new MethodCall("passivateObject", obj));
    removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here.
    assertEquals(expectedMethods, factory.getMethodCalls());
    assertEquals(1, pool.getNumIdle());   // Not returned
    assertEquals(1, pool.getNumActive()); // But not in active count

    // destroyObject should swallow exceptions too
    reset(pool, factory, expectedMethods);
    obj = pool.borrowObject();
    clear(factory, expectedMethods);
    factory.setPassivateObjectFail(true);
    factory.setDestroyObjectFail(true);
    pool.returnObject(obj);
    pool.close();
}