Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.apache.commons.pool.impl;
 
 
A simple, Stack-based org.apache.commons.pool.ObjectPool implementation.

Given a org.apache.commons.pool.PoolableObjectFactory, this class will maintain a simple pool of instances. A finite number of "sleeping" or idle instances is enforced, but when the pool is empty, new instances are created to support the new load. Hence this class places no limit on the number of "active" instances created by the pool, but is quite useful for re-using Objects without introducing artificial limits.

Parameters:
<T> the type of objects held in this pool
Author(s):
Rodney Waldhoff
Dirk Verbeeck
Sandy McArthur
Version:
$Revision: 1222396 $ $Date: 2011-12-22 14:02:25 -0500 (Thu, 22 Dec 2011) $
Since:
Pool 1.0
 
 public class StackObjectPool<T> extends BaseObjectPool<T> implements ObjectPool<T> {
    
Create a new pool using no factory. Clients must first set the factory or else this pool will not behave correctly. Clients may first populate the pool using returnObject(java.lang.Object) before they can be borrowed but this usage is discouraged.

 
     @Deprecated
     public StackObjectPool() {
     }

    
Create a new pool using no factory. Clients must first set the factory or else this pool will not behave correctly. Clients may first populate the pool using returnObject(java.lang.Object) before they can be borrowed but this usage is discouraged.

Deprecated:
to be removed in pool 2.0 - use StackObjectPool(org.apache.commons.pool.PoolableObjectFactory,int)
Parameters:
maxIdle cap on the number of "sleeping" instances in the pool
See also:
StackObjectPool(org.apache.commons.pool.PoolableObjectFactory,int)
 
     @Deprecated
     public StackObjectPool(int maxIdle) {
         this(null,maxIdle,);
     }

    
Create a new pool using no factory. Clients must first set the factory or else this pool will not behave correctly. Clients may first populate the pool using returnObject(java.lang.Object) before they can be borrowed but this usage is discouraged.

Deprecated:
to be removed in pool 2.0 - use StackObjectPool(org.apache.commons.pool.PoolableObjectFactory,int,int)
Parameters:
maxIdle cap on the number of "sleeping" instances in the pool
initIdleCapacity initial size of the pool (this specifies the size of the container, it does not cause the pool to be pre-populated.)
See also:
StackObjectPool(org.apache.commons.pool.PoolableObjectFactory,int,int)
 
     @Deprecated
     public StackObjectPool(int maxIdleint initIdleCapacity) {
         this(null,maxIdle,initIdleCapacity);
     }

    
Create a new StackObjectPool using the specified factory to create new instances.

Parameters:
factory the org.apache.commons.pool.PoolableObjectFactory used to populate the pool
    public StackObjectPool(PoolableObjectFactory<T> factory) {
    }

    
Create a new SimpleObjectPool using the specified factory to create new instances, capping the number of "sleeping" instances to maxIdle.

Parameters:
factory the org.apache.commons.pool.PoolableObjectFactory used to populate the pool
maxIdle cap on the number of "sleeping" instances in the pool
    public StackObjectPool(PoolableObjectFactory<T> factoryint maxIdle) {
        this(factory,maxIdle,);
    }

    

Create a new StackObjectPool using the specified factory to create new instances, capping the number of "sleeping" instances to maxIdle, and initially allocating a container capable of containing at least initIdleCapacity instances. The pool is not pre-populated. The initIdleCapacity parameter just determines the initial size of the underlying container, which can increase beyond this value if maxIdle > initIdleCapacity.

Negative values of maxIdle are ignored (i.e., the pool is created using DEFAULT_MAX_SLEEPING) as are non-positive values for initIdleCapacity.

Parameters:
factory the org.apache.commons.pool.PoolableObjectFactory used to populate the pool
maxIdle cap on the number of "sleeping" instances in the pool
initIdleCapacity initial size of the pool (this specifies the size of the container, it does not cause the pool to be pre-populated.)
    public StackObjectPool(PoolableObjectFactory<T> factoryint maxIdleint initIdleCapacity) {
         = factory;
         = (maxIdle < 0 ?  : maxIdle);
        int initcapacity = (initIdleCapacity < 1 ?  : initIdleCapacity);
         = new Stack<T>();
        .ensureCapacityinitcapacity >  ?  : initcapacity);
    }

    

Borrows an object from the pool. If there are idle instances available on the stack, the top element of the stack is popped to activate, validate and return to the client. If there are no idle instances available, the makeObject method of the pool's org.apache.commons.pool.PoolableObjectFactory is invoked to create a new instance.

All instances are activated and validated before being returned to the client. If validation fails or an exception occurs activating or validating an instance popped from the idle instance stack, the failing instance is destroyed and the next instance on the stack is popped, validated and activated. This process continues until either the stack is empty or an instance passes validation. If the stack is empty on activation or it does not contain any valid instances, the factory's makeObject method is used to create a new instance. If a null instance is returned by the factory or the created instance either raises an exception on activation or fails validation, NoSuchElementException is thrown. Exceptions thrown by MakeObject are propagated to the caller; but other than ThreadDeath or VirtualMachineError, exceptions generated by activation, validation or destroy methods are swallowed silently.

Returns:
an instance from the pool
    @Override
    public synchronized T borrowObject() throws Exception {
        assertOpen();
        T obj = null;
        boolean newlyCreated = false;
        while (null == obj) {
            if (!.empty()) {
                obj = .pop();
            } else {
                if(null == ) {
                    throw new NoSuchElementException();
                } else {
                    obj = .makeObject();
                    newlyCreated = true;
                  if (obj == null) {
                    throw new NoSuchElementException("PoolableObjectFactory.makeObject() returned null.");
                  }
                }
            }
            if (null !=  && null != obj) {
                try {
                    .activateObject(obj);
                    if (!.validateObject(obj)) {
                        throw new Exception("ValidateObject failed");
                    }
                } catch (Throwable t) {
                    PoolUtils.checkRethrow(t);
                    try {
                        .destroyObject(obj);
                    } catch (Throwable t2) {
                        PoolUtils.checkRethrow(t2);
                        // swallowed
                    } finally {
                        obj = null;
                    }
                    if (newlyCreated) {
                        throw new NoSuchElementException(
                            "Could not create a validated object, cause: " +
                            t.getMessage());
                    }
                }
            }
        }
        ++;
        return obj;
    }

    

Returns an instance to the pool, pushing it on top of the idle instance stack after successful validation and passivation. The returning instance is destroyed if any of the following are true:

  • the pool is closed
  • validation fails
  • passivation throws an exception
If adding a validated, passivated returning instance to the stack would cause maxSleeping to be exceeded, the oldest (bottom) instance on the stack is destroyed to make room for the returning instance, which is pushed on top of the stack.

Exceptions passivating or destroying instances are silently swallowed. Exceptions validating instances are propagated to the client.

Parameters:
obj instance to return to the pool
    @Override
    public synchronized void returnObject(T objthrows Exception {
        boolean success = !isClosed();
        if(null != ) {
            if(!.validateObject(obj)) {
                success = false;
            } else {
                try {
                    .passivateObject(obj);
                } catch(Exception e) {
                    success = false;
                }
            }
        }
        boolean shouldDestroy = !success;
        --;
        if (success) {
            T toBeDestroyed = null;
            if(.size() >= ) {
                shouldDestroy = true;
                toBeDestroyed = .remove(0); // remove the stalest object
            }
            .push(obj);
            obj = toBeDestroyed// swap returned obj with the stalest one so it can be destroyed
        }
        notifyAll(); // _numActive has changed
        if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null
            try {
                .destroyObject(obj);
            } catch(Exception e) {
                // ignored
            }
        }
    }

    
    @Override
    public synchronized void invalidateObject(T objthrows Exception {
        --;
        if (null != ) {
            .destroyObject(obj);
        }
        notifyAll(); // _numActive has changed
    }

    
Return the number of instances currently idle in this pool.

Returns:
the number of instances currently idle in this pool
    @Override
    public synchronized int getNumIdle() {
        return .size();
    }

    
Return the number of instances currently borrowed from this pool.

Returns:
the number of instances currently borrowed from this pool
    @Override
    public synchronized int getNumActive() {
        return ;
    }

    
Clears any objects sitting idle in the pool. Silently swallows any exceptions thrown by org.apache.commons.pool.PoolableObjectFactory.destroyObject(java.lang.Object).
    @Override
    public synchronized void clear() {
        if(null != ) {
            Iterator<T> it = .iterator();
            while(it.hasNext()) {
                try {
                    .destroyObject(it.next());
                } catch(Exception e) {
                    // ignore error, keep destroying the rest
                }
            }
        }
        .clear();
    }

    

Close this pool, and free any resources associated with it. Invokes clear() to destroy and remove instances in the pool.

Calling addObject() or borrowObject() after invoking this method on a pool will cause them to throw an java.lang.IllegalStateException.

Throws:
java.lang.Exception never - exceptions clearing the pool are swallowed
    @Override
    public void close() throws Exception {
        super.close();
        clear();
    }

    

Create an object, and place it on top of the stack. This method is useful for "pre-loading" a pool with idle objects.

Before being added to the pool, the newly created instance is validated and passivated. If validation fails, the new instance is destroyed. Exceptions generated by the factory makeObject or passivate are propagated to the caller. Exceptions destroying instances are silently swallowed.

If a new instance is created and successfully validated and passivated and adding this instance to the pool causes maxSleeping to be exceeded, the oldest (bottom) instance in the pool is destroyed to make room for the newly created instance, which is pushed on top of the stack.

Throws:
java.lang.Exception when the factory has a problem creating or passivating an object.
    @Override
    public synchronized void addObject() throws Exception {
        assertOpen();
        if ( == null) {
            throw new IllegalStateException("Cannot add objects without a factory.");
        }
        T obj = .makeObject();
        boolean success = true;
        if(!.validateObject(obj)) {
            success = false;
        } else {
            .passivateObject(obj);
        }
        boolean shouldDestroy = !success;
        if (success) {
            T toBeDestroyed = null;
            if(.size() >= ) {
                shouldDestroy = true;
                toBeDestroyed = .remove(0); // remove the stalest object
            }
            .push(obj);
            obj = toBeDestroyed// swap returned obj with the stalest one so it can be destroyed
        }
        notifyAll(); // _numIdle has changed
        if(shouldDestroy) { // by constructor, shouldDestroy is false when _factory is null
            try {
                .destroyObject(obj);
            } catch(Exception e) {
                // ignored
            }
        }
    }

    
Sets the factory this pool uses to create new instances. Trying to change the factory while there are borrowed objects will throw an java.lang.IllegalStateException.

Deprecated:
to be removed in pool 2.0
Parameters:
factory the org.apache.commons.pool.PoolableObjectFactory used to create new instances.
Throws:
java.lang.IllegalStateException when the factory cannot be set at this time
    @Deprecated
    @Override
    public synchronized void setFactory(PoolableObjectFactory<T> factorythrows IllegalStateException {
        assertOpen();
        if(0 < getNumActive()) {
            throw new IllegalStateException("Objects are already active");
        } else {
            clear();
             = factory;
        }
    }

    
The cap on the number of "sleeping" instances in the pool.
    protected static final int DEFAULT_MAX_SLEEPING  = 8;

    
The default initial size of the pool (this specifies the size of the container, it does not cause the pool to be pre-populated.)
    protected static final int DEFAULT_INIT_SLEEPING_CAPACITY = 4;

    
My pool.

Deprecated:
to be made private in pool 2.0
    @Deprecated
    protected Stack<T> _pool = null;

    
My org.apache.commons.pool.PoolableObjectFactory.

Deprecated:
to be made private in pool 2.0 - use getFactory()
    @Deprecated
    protected PoolableObjectFactory<T> _factory = null;

    
The cap on the number of "sleeping" instances in the pool.

Deprecated:
to be made private in pool 2.0 - use getMaxSleeping()
    @Deprecated
    protected int _maxSleeping = ;
    
    
Number of objects borrowed but not yet returned to the pool.

Deprecated:
to be made private in pool 2.0 - use getNumActive()
    @Deprecated
    protected int _numActive = 0;

    
Returns the org.apache.commons.pool.PoolableObjectFactory used by this pool to create and manage object instances.

Returns:
the factory
Since:
1.5.5
    public synchronized PoolableObjectFactory<T> getFactory() {
        return ;
    }

    
Returns the maximum number of idle instances in the pool.

Returns:
maxSleeping
Since:
1.5.5
    public int getMaxSleeping() {
        return ;
    }
   
New to GrepCode? Check out our FAQ X