Example usage for org.apache.commons.pool ObjectPool returnObject

List of usage examples for org.apache.commons.pool ObjectPool returnObject

Introduction

In this page you can find the example usage for org.apache.commons.pool ObjectPool returnObject.

Prototype

void returnObject(Object p0) throws Exception;

Source Link

Usage

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.
 *///  w ww.jav  a2s  . 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

/**
 * Returns the given object to the pool.
 *
 * @param pool   The pool to where return the object to.
 * @param object The object to be returned to the pool.
 *//*from  w w  w.  java2  s  .com*/
private void returnObject(ObjectPool<Classifier> pool, Classifier object) {
    try {
        pool.returnObject(object);
    } catch (Exception e) {
        logger.error("Could not return object to pool", e);
    }
}

From source file:net.jradius.server.Processor.java

public void process() throws Exception {
    Object queueElement = this.queue.take();

    if (!(queueElement instanceof ListenerRequest)) {
        throw new IllegalArgumentException(
                "Expected ListenerRequest but found " + queueElement.getClass().getName());
    }/*  www.j a  va  2  s  . c  o  m*/

    ListenerRequest request = (ListenerRequest) queueElement;

    try {
        processRequest(request);
    } finally {
        ObjectPool pool = request.getBorrowedFromPool();

        if (pool != null) {
            pool.returnObject(request);
        }
    }
}

From source file:com.meidusa.amoeba.net.poolable.MultipleLoadBalanceObjectPool.java

public void returnObject(Object obj) throws Exception {
    PoolableObject poolableObject = (PoolableObject) obj;
    ObjectPool pool = poolableObject.getObjectPool();
    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/*from   w w  w .  jav a 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 testPOFReturnObjectUsages() throws Exception {
    final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
    final ObjectPool pool;
    try {//from w w w  .j a  va2  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:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java

public void testPOFBorrowObjectUsages() throws Exception {
    final MethodCallPoolableObjectFactory factory = new MethodCallPoolableObjectFactory();
    final ObjectPool pool;
    try {// w ww  . ja  v a  2s .c o 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:edu.illinois.enforcemop.examples.apache.pool.TestObjectPool.java

public void testClosedPoolBehavior() throws Exception {
    final ObjectPool pool;
    try {//from  w  ww.  j a v  a2 s.  c o m
        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:org.apache.ojb.broker.accesslayer.ConnectionFactoryPooledImpl.java

public void releaseJdbcConnection(JdbcConnectionDescriptor jcd, Connection con) throws LookupException {
    final ObjectPool op = (ObjectPool) poolMap.get(jcd.getPBKey());
    try {//from   w w w .j av a 2 s  .co m
        /* mkalen: NB - according to the Commons Pool API we should _not_ perform
         * any additional checks here since we will then break testOnX semantics
         *
         * To enable Connection validation on releaseJdbcConnection,
         * set a validation query and specify testOnRelease=true
         *
         * Destruction of pooled objects is performed by the actual Commons Pool
         * ObjectPool implementation when the object factory's validateObject method
         * returns false. See ConPoolFactory#validateObject.
         */
        op.returnObject(con);
    } catch (Exception e) {
        throw new LookupException(e);
    }
}

From source file:org.jvoicexml.implementation.pool.KeyedResourcePool.java

/**
 * Returns a previously borrowed resource to the pool.
 * @param key resource type.//ww w  .j a va 2 s  .c  om
 * @param resource resource to return.
 * @throws NoresourceError
 *         Error returning the object to the pool.
 * @since 0.6
 */
public synchronized void returnObject(final String key, final T resource) throws NoresourceError {
    final ObjectPool pool = pools.get(key);
    if (pool == null) {
        throw new NoresourceError("Pool of type '" + key + "' is unknown!");
    }
    try {
        pool.returnObject(resource);
    } catch (Exception e) {
        throw new NoresourceError(e.getMessage(), e);
    }
    LOGGER.info("returned object of type '" + key + "' (" + resource.getClass().getCanonicalName() + ")");

    if (LOGGER.isDebugEnabled()) {
        final int active = pool.getNumActive();
        final int idle = pool.getNumIdle();
        LOGGER.debug("pool has now " + active + " active/" + idle + " idle for key '" + key + "' ("
                + resource.getClass().getCanonicalName() + ") after return");
    }
}