當前位置: 首頁>>代碼示例>>Java>>正文


Java ObjectPool.borrowObject方法代碼示例

本文整理匯總了Java中org.apache.commons.pool2.ObjectPool.borrowObject方法的典型用法代碼示例。如果您正苦於以下問題:Java ObjectPool.borrowObject方法的具體用法?Java ObjectPool.borrowObject怎麽用?Java ObjectPool.borrowObject使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.pool2.ObjectPool的用法示例。


在下文中一共展示了ObjectPool.borrowObject方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getConnection

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
/**
 * 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);
	}
}
 
開發者ID:Derek-Ashmore,項目名稱:moneta,代碼行數:23,代碼來源:MonetaConfiguration.java

示例2: invoke

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@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);
}
 
開發者ID:ketao1989,項目名稱:ourea,代碼行數:40,代碼來源:ConsumerProxy.java

示例3: testBasicHappyPath

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@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() );
}
 
開發者ID:Derek-Ashmore,項目名稱:moneta,代碼行數:10,代碼來源:ConnectionPoolFactoryTest.java

示例4: borrowAndReturn

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
private void borrowAndReturn(ObjectPool<StatefulRedisConnection<String, String>> pool) throws Exception {

        for (int i = 0; i < 10; i++) {
            StatefulRedisConnection<String, String> connection = pool.borrowObject();
            RedisCommands<String, String> sync = connection.sync();
            sync.ping();
            pool.returnObject(connection);
        }
    }
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:10,代碼來源:ConnectionPoolSupportTest.java

示例5: borrowAndCloseTryWithResources

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
private void borrowAndCloseTryWithResources(ObjectPool<StatefulRedisConnection<String, String>> pool) throws Exception {

        for (int i = 0; i < 10; i++) {
            try (StatefulRedisConnection<String, String> connection = pool.borrowObject()) {
                RedisCommands<String, String> sync = connection.sync();
                sync.ping();
            }
        }
    }
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:10,代碼來源:ConnectionPoolSupportTest.java

示例6: borrowAndClose

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
private void borrowAndClose(ObjectPool<StatefulRedisConnection<String, String>> pool) throws Exception {

        for (int i = 0; i < 10; i++) {
            StatefulRedisConnection<String, String> connection = pool.borrowObject();
            RedisCommands<String, String> sync = connection.sync();
            sync.ping();
            sync.close();
        }
    }
 
開發者ID:lettuce-io,項目名稱:lettuce-core,代碼行數:10,代碼來源:ConnectionPoolSupportTest.java

示例7: testPOFInvalidateObjectUsages

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@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 defered
    removeDestroyObjectCall(factory.getMethodCalls());
    assertEquals(expectedMethods, factory.getMethodCalls());
    pool.close();
}
 
開發者ID:apache,項目名稱:commons-pool,代碼行數:39,代碼來源:TestObjectPool.java

示例8: PersistenceProcessorImpl

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@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.lowWatermarkWriter = commitTable.getWriter();
    this.batchSequence = 0L;
    this.batchPool = batchPool;
    this.currentBatch = batchPool.borrowObject();
    // Low Watermark writer
    ThreadFactoryBuilder lwmThreadFactory = new ThreadFactoryBuilder().setNameFormat("lwm-writer-%d");
    this.lowWatermarkWriterExecutor = Executors.newSingleThreadExecutor(lwmThreadFactory.build());

    // Metrics config
    this.lwmWriteTimer = metrics.timer(name("tso", "lwmWriter", "latency"));

    LOG.info("PersistentProcessor initialized");

}
 
開發者ID:apache,項目名稱:incubator-omid,代碼行數:42,代碼來源:PersistenceProcessorImpl.java

示例9: parseScan

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@Override
public IScan parseScan(int num, boolean parseSpectrum) throws FileParsingException {
    // prepare for parsing
    NavigableMap<Integer, ? extends XMLBasedIndexElement> idx = fetchIndex().getMapByNum();
    XMLBasedIndexElement indexElement = idx.get(num);
    if (indexElement == null)
        throw new FileParsingException(String.format("No such scan number found in the index [%d]", num));
    OffsetLength offsetLength = indexElement.getOffsetLength();
    if (offsetLength == null) {
        throw new IllegalArgumentException("The scan you've requested to parse spectrumRef for was not found in the index");
    }
    ByteArrayHolder bah = null;
    ObjectPool<ByteArrayHolder> pool = PooledByteArrayHolders.getInstance().getPool();
    try {
        long offset = offsetLength.offset;
        int length = offsetLength.length;
        // get a read buffer
        bah = pool.borrowObject();
        bah.ensureCapacity(length);
        // do the read IO
        RandomAccessFile raf = this.getRandomAccessFile();
        raf.seek(offset);
        raf.readFully(bah.getUnderlyingBytes(), 0, length);
        bah.setPosition(length); // just to make sure, that BAH knows the valid data range
        // we've read the whole scan from file, wrap it into a ByteStream and pass to the parser
        ByteArrayInputStream is = new ByteArrayInputStream(bah.getUnderlyingBytes(), 0, length);

        // This is just a trick to fool the parser into parsing everything.
        // It doesn't cause any trouble, as we've only read a single scan from the file.
        LCMSDataSubset subset = LCMSDataSubset.WHOLE_RUN;
        if (!parseSpectrum) {
            subset = LCMSDataSubset.STRUCTURE_ONLY;
        }
        MultiSpectraParser parser = getSpectraParser(is, subset, readerPool, 1);
        List<IScan> scansParsed = parser.call();
        if (scansParsed == null || scansParsed.isEmpty()) {
            throw new FileParsingException("Could not parse a single spectrumRef from the file");
        }
        if (scansParsed.size() != 1) {
            throw new FileParsingException("Somehow more than one scan was parsed, when we tried to parse a single spectrumRef");
        }
        return scansParsed.get(0);
    } catch (Exception e) {
        throw new FileParsingException(e);
    } finally {
        if (bah != null) {
            try {
                pool.returnObject(bah);
            } catch (Exception ex) {
                throw new FileParsingException("Could not return a byte array holder back to the pool", ex);
            }
        }
        this.close();
    }
}
 
開發者ID:chhh,項目名稱:MSFTBX,代碼行數:56,代碼來源:AbstractXMLBasedDataSource.java

示例10: testPOFReturnObjectUsages

import org.apache.commons.pool2.ObjectPool; //導入方法依賴的package包/類
@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();
}
 
開發者ID:apache,項目名稱:commons-pool,代碼行數:61,代碼來源:TestObjectPool.java


注:本文中的org.apache.commons.pool2.ObjectPool.borrowObject方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。