List of usage examples for org.apache.commons.pool ObjectPool borrowObject
Object borrowObject() throws Exception;
From source file:com.spokentech.speechdown.server.util.pool.AbstractPoolableObjectFactory.java
/** * Initializes an {@link org.apache.commons.pool.ObjectPool} by borrowing each object from the * pool (thereby triggering activation) and then returning all the objects back to the pool. * @param pool the object pool to be initialized. * @throws InstantiationException if borrowing (or returning) an object from the pool triggers an exception. *//*from w ww . j a v a 2 s. co m*/ public static void initPool(ObjectPool pool) throws InstantiationException { try { List<Object> objects = new ArrayList<Object>(); while (true) try { objects.add(pool.borrowObject()); } catch (NoSuchElementException e) { // ignore, max active reached break; } for (Object obj : objects) { pool.returnObject(obj); } } catch (Exception e) { try { pool.close(); } catch (Exception e1) { _logger.warn("Encounter expception while attempting to close object pool!", e1); } throw (InstantiationException) new InstantiationException(e.getMessage()).initCause(e); } }
From source file:com.feedzai.fos.impl.weka.utils.WekaThreadSafeScorerPool.java
/** * The the given <code>Object[]</code> with this scorer (thread safe!). * <p/>// w ww . j a v a 2 s .c o m * The score in bound by the configuration <code>minScore</code> and <code>maxScore</code>. * * * @param scorable the scorable data to score * @return the score value already bound the configuration range * @throws FOSException when classification was not possible */ @Override public double[] score(Object[] scorable) throws FOSException { /* the pool can change while this is processing (reload) so assign a local variable */ final ObjectPool<Classifier> localPool = pool; Classifier classifier = null; try { classifier = localPool.borrowObject(); return WekaUtils.score(classifier, scorable, instanceSetters, instances, attributes); } catch (Exception e) { throw new FOSException(e); } finally { returnObject(localPool, classifier); } }
From source file:gov.nih.nci.firebird.proxy.FaultTolerantProxyFactoryTest.java
private void verifyProxyChain(TestClientI wrappedClient) throws Exception { assertTrue(Proxy.isProxyClass(wrappedClient.getClass())); RetryHandler retryHandler = (RetryHandler) Proxy.getInvocationHandler(wrappedClient); Provider<TestClientI> provider = (Provider<TestClientI>) retryHandler.getClientProvider(); TestClientI pooledClient = provider.get(); assertTrue(Proxy.isProxyClass(pooledClient.getClass())); PoolingHandler poolingHandler = (PoolingHandler) Proxy.getInvocationHandler(pooledClient); ObjectPool<Object> pool = poolingHandler.getPool(); TestClientI client = (TestClientI) pool.borrowObject(); assertNotNull(client);//from w ww . j ava 2s . co m assertTrue(retryHandler.getValidExceptions().containsAll(VALID_EXCEPTIONS)); assertTrue(poolingHandler.getValidExceptions().containsAll(VALID_EXCEPTIONS)); }
From source file:com.honnix.jaxo.core.internal.services.PoolableCoreServiceImpl.java
@Override public Validator getValidator(Schema schema) { /*/* w w w . ja va 2s . com*/ * this looks stupid but to avoid lock, hope creating a GenericObjectPool does not cost too much * java suck with no lazy evaluation support */ validatorObjectPoolMap.putIfAbsent(schema, new GenericObjectPool<Validator>(new ValidatorObjectFactory(schema), validatorConfig)); ObjectPool<Validator> validatorObjectPool = validatorObjectPoolMap.get(schema); try { return validatorObjectPool.borrowObject(); } catch (Exception e) { throw new JAXOException(e.getMessage(), e); } }
From source file:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java
public void testClosedPoolBehavior() throws Exception { final ObjectPool pool; try {//w w w. ja va2 s. com pool = makeEmptyPool(new MethodCallPoolableObjectFactory()); } catch (UnsupportedOperationException uoe) { return; // test not supported } Object o1 = pool.borrowObject(); Object o2 = pool.borrowObject(); pool.close(); try { pool.addObject(); fail("A closed pool must throw an IllegalStateException when addObject is called."); } catch (IllegalStateException ise) { // expected } try { pool.borrowObject(); fail("A closed pool must throw an IllegalStateException when borrowObject is called."); } catch (IllegalStateException ise) { // expected } // The following should not throw exceptions just because the pool is closed. if (pool.getNumIdle() >= 0) { assertEquals("A closed pool shouldn't have any idle objects.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 2, pool.getNumActive()); } pool.returnObject(o1); if (pool.getNumIdle() >= 0) { assertEquals("returnObject should not add items back into the idle object pool for a closed pool.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 1, pool.getNumActive()); } pool.invalidateObject(o2); if (pool.getNumIdle() >= 0) { assertEquals("invalidateObject must not add items back into the idle object pool.", 0, pool.getNumIdle()); } if (pool.getNumActive() >= 0) { assertEquals("A closed pool should still keep count of active objects.", 0, pool.getNumActive()); } pool.clear(); pool.close(); }
From source file:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java
public void testPOFInvalidateObjectUsages() throws Exception { final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory(); final ObjectPool pool; try {// w ww . ja v a2 s. c om pool = makeEmptyPool(factory); } catch (UnsupportedOperationException uoe) { return; // test not supported } final List 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 (PrivateException ex) { // Expected } Thread.sleep(250); // could be defered removeDestroyObjectCall(factory.getMethodCalls()); assertEquals(expectedMethods, factory.getMethodCalls()); }
From source file:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java
public void testPOFReturnObjectUsages() throws Exception { final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory(); final ObjectPool pool; try {// ww w . jav a 2 s. co m pool = makeEmptyPool(factory); } catch (UnsupportedOperationException uoe) { return; // test not supported } final List 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 StackObjectPool || 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 StackObjectPool || 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); }
From source file:net.sf.hajdbc.pool.generic.GenericObjectPoolFactory.java
@Override public <T, E extends Exception> Pool<T, E> createPool(final PoolProvider<T, E> provider) { PoolableObjectFactory<T> factory = new PoolableObjectFactory<T>() { @Override// w ww .j a va 2 s . com public void destroyObject(T object) { provider.close(object); } @Override public T makeObject() throws Exception { return provider.create(); } @Override public boolean validateObject(T object) { return provider.isValid(object); } @Override public void activateObject(T object) { } @Override public void passivateObject(T object) { } }; final ObjectPool<T> pool = new GenericObjectPool<T>(factory, this.config); return new Pool<T, E>() { @Override public void close() { try { pool.close(); } catch (Exception e) { logger.log(Level.WARN, e, e.getMessage()); } } @Override public void release(T item) { try { pool.returnObject(item); } catch (Exception e) { logger.log(Level.WARN, e, e.getMessage()); } } @Override public T take() throws E { try { return pool.borrowObject(); } catch (NoSuchElementException e) { return provider.create(); } catch (IllegalStateException e) { throw e; } catch (Exception e) { throw provider.getExceptionClass().cast(e); } } }; }
From source file:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java
public void testPOFBorrowObjectUsages() throws Exception { final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory(); final ObjectPool pool; try {/*from w w w.j a v a 2s . co m*/ pool = makeEmptyPool(factory); } catch (UnsupportedOperationException uoe) { return; // test not supported } if (pool instanceof GenericObjectPool) { ((GenericObjectPool) pool).setTestOnBorrow(true); } final List expectedMethods = new ArrayList(); Object obj; /// Test correct behavior code paths // existing idle object should be activated and validated pool.addObject(); clear(factory, expectedMethods); obj = pool.borrowObject(); expectedMethods.add(new MethodCall("activateObject", ZERO)); expectedMethods.add(new MethodCall("validateObject", ZERO).returned(Boolean.TRUE)); assertEquals(expectedMethods, factory.getMethodCalls()); pool.returnObject(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(); fail("Expected borrowObject to propagate makeObject exception."); } catch (PrivateException pe) { // expected } expectedMethods.add(new MethodCall("makeObject")); assertEquals(expectedMethods, factory.getMethodCalls()); // when activateObject fails in borrowObject, a new object should be borrowed/created reset(pool, factory, expectedMethods); pool.addObject(); clear(factory, expectedMethods); factory.setActivateObjectFail(true); expectedMethods.add(new MethodCall("activateObject", obj)); try { obj = pool.borrowObject(); fail("Expecting NoSuchElementException"); } catch (NoSuchElementException ex) { // Expected - newly created object will also fail to activate } // Idle object fails activation, new one created, also fails expectedMethods.add(new MethodCall("makeObject").returned(ONE)); expectedMethods.add(new MethodCall("activateObject", ONE)); 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(); clear(factory, expectedMethods); factory.setValidateObjectFail(true); expectedMethods.add(new MethodCall("activateObject", ZERO)); expectedMethods.add(new MethodCall("validateObject", ZERO)); try { obj = pool.borrowObject(); } catch (NoSuchElementException ex) { // Expected - newly created object will also fail to validate } // Idle object is activated, but fails validation. // New instance is created, activated and then fails validation expectedMethods.add(new MethodCall("makeObject").returned(ONE)); expectedMethods.add(new MethodCall("activateObject", ONE)); expectedMethods.add(new MethodCall("validateObject", ONE)); removeDestroyObjectCall(factory.getMethodCalls()); // The exact timing of destroyObject is flexible here. // Second activate and validate are missing from expectedMethods assertTrue(factory.getMethodCalls().containsAll(expectedMethods)); }
From source file:com.meidusa.amoeba.net.poolable.MultipleLoadBalanceObjectPool.java
public Object borrowObject() throws Exception { ObjectPool pool = null; ObjectPool[] poolsTemp = null;//from ww w .j a v a2 s. co m while (true) { poolsTemp = runtimeObjectPools; if (poolsTemp.length == 0) { throw new Exception("poolName=" + name + ", no valid pools"); } if (loadbalance == LOADBALANCING_ROUNDROBIN) { long current = currentCount.getAndIncrement(); pool = poolsTemp[(int) (current % poolsTemp.length)]; } else if (loadbalance == LOADBALANCING_WEIGHTBASED) { if (poolsTemp.length > 1) { ObjectPool[] objectPoolsCloned = poolsTemp.clone(); Arrays.sort(objectPoolsCloned, comparator); pool = objectPoolsCloned[0]; } else if (poolsTemp.length == 1) { pool = poolsTemp[0]; } } else if (loadbalance == LOADBALANCING_HA) { // HA,pool if (index < poolsTemp.length) { pool = poolsTemp[index]; } else { pool = poolsTemp[0]; } } else { throw new Exception( "poolName=" + name + " loadbalance parameter error,parameter loadbalance in [1,2,3]"); } if (!pool.isValid()) { validate(); continue; } else { break; } } return pool.borrowObject(); }