/*
 * $Header: /home/cvs/commons/pool-1.0.1/ja/src/org/apache/commons/pool/impl/StackObjectPool.java,v 1.1.1.1 2004/02/13 10:02:01 hioki Exp $
 * $Revision: 1.1.1.1 $
 * $Date: 2004/02/13 10:02:01 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Commons", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.commons.pool.impl;

import org.apache.commons.pool.*;
import java.util.Stack;
import java.util.NoSuchElementException;
import java.util.Enumeration;

/**
 * {@link java.util.Stack Stack} をベースにしたシンプルな {@link ObjectPool} の実装です。
 * {@primary A simple, {@link java.util.Stack Stack}-based {@link ObjectPool} implementation.}
 * <p>
 * {@link PoolableObjectFactory} を渡されることにより、
 * このクラスはシンプルなインスタンスのプールを管理します。
 * "休止した"または未使用のインスタンスの数は制限されますが、
 * プールが空の場合には新たな取得要求にこたえるために新たなインスタンスが生成されます。
 * 従ってこのクラスプールによって生成された"使用中"のインスタンスを数の制限なく持つことができますが、
 * 不自然な制限をかけることなしに <tt>Object</tt> の再利用を行う際に非常に有用です。
 * {@primary Given a {@link 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 <tt>Object</tt>s without introducing
 * artificial limits.}
 *
 * @author Rodney Waldhoff
 * @translator 日置 聡
 * @status firstdraft
 * @update 2003/08/21
 * @version $Revision: 1.1.1.1 $ $Date: 2004/02/13 10:02:01 $
 */
public class StackObjectPool extends BaseObjectPool implements ObjectPool {
    /**
     * ファクトリを使用せずに新たなプールを生成します。
     * クライアントは {@link #borrowObject 取得} を行う前にあらかじめ
     * {@link #returnObject(java.lang.Object)}
     * を使ってプールにインスタンスを登録しておく必要があります。
     * {@primary Create a new pool using
     * no factory. Clients must first populate the pool
     * using {@link #returnObject(java.lang.Object)}
     * before they can be {@link #borrowObject borrowed}.}
     */
    public StackObjectPool() {
        this((PoolableObjectFactory)null,DEFAULT_MAX_SLEEPING,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * ファクトリを使用せずに新たなプールを生成します。
     * クライアントは {@link #borrowObject 取得} を行う前にあらかじめ
     * {@link #returnObject(java.lang.Object)}
     * を使ってプールにインスタンスを登録しておく必要があります。
     * {@primary Create a new pool using
     * no factory. Clients must first populate the pool
     * using {@link #returnObject(java.lang.Object)}
     * before they can be {@link #borrowObject borrowed}.}
     */
    public StackObjectPool(int max) {
        this((PoolableObjectFactory)null,max,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * ファクトリを使用せずに新たなプールを生成します。
     * クライアントは {@link #borrowObject 取得} を行う前にあらかじめ
     * {@link #returnObject(java.lang.Object)}
     * を使ってプールにインスタンスを登録しておく必要があります。
     * {@primary Create a new pool using
     * no factory. Clients must first populate the pool
     * using {@link #returnObject(java.lang.Object)}
     * before they can be {@link #borrowObject borrowed}.}
     */
    public StackObjectPool(int max, int init) {
        this((PoolableObjectFactory)null,max,init);
    }

    /**
     * 指定された <i>factory</i> を新規インスタンスの生成に使用する、新たな
     * <tt>StackObjectPool</tt> を生成します。
     * {@primary Create a new <tt>StackObjectPool</tt> using
     * the specified <i>factory</i> to create new instances.}
     *
     * @param factory プールで使用される {@link PoolableObjectFactory}
     * {@primary the {@link PoolableObjectFactory} used to populate the pool}
     */
    public StackObjectPool(PoolableObjectFactory factory) {
        this(factory,DEFAULT_MAX_SLEEPING,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * 指定された <i>factory</i> を新規インスタンスの生成に使用し、
     * "休止した"インスタンスの数を <i>max</i> に制限する、新たな
     * <tt>StackObjectPool</tt> を生成します。
     * {@primary Create a new <tt>SimpleObjectPool</tt> using
     * the specified <i>factory</i> to create new instances,
     * capping the number of "sleeping" instances to <i>max</i>}
     *
     * @param factory プールで使用される {@link PoolableObjectFactory}
     * {@primary the {@link PoolableObjectFactory} used to populate the pool}
     * @param max プール内の"休止した"インスタンスの数の上限
     * {@primary cap on the number of "sleeping" instances in the pool}
     */
    public StackObjectPool(PoolableObjectFactory factory, int max) {
        this(factory,max,DEFAULT_INIT_SLEEPING_CAPACITY);
    }

    /**
     * 指定された <i>factory</i> を新規インスタンスの生成に使用し、
     * "休止した"インスタンスの数を <i>max</i> に制限し、
     * 初期化時に少なくとも <i>init</i> 個のインスタンスを格納できる容量を確保する、新たな
     * <tt>StackObjectPool</tt> を生成します。
     * {@primary Create a new <tt>SimpleObjectPool</tt> using
     * the specified <i>factory</i> to create new instances,
     * capping the number of "sleeping" instances to <i>max</i>,
     * and initially allocating a container capable of containing
     * at least <i>init</i> instances.}
     *
     * @param factory プールで使用される {@link PoolableObjectFactory}
     * {@primary the {@link PoolableObjectFactory} used to populate the pool}
     * @param max プール内の "休止した" インスタンスの数の上限
     * {@primary cap on the number of "sleeping" instances in the pool}
     * @param init プールの初期サイズ (これは容量の大きさを指し、事前にプール内にインスタンスを生成するわけではありません)
     *{@primary 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 factory, int max, int init) {
        _factory = factory;
        _maxSleeping = (max < 0 ? DEFAULT_MAX_SLEEPING : max);
        int initcapacity = (init < 1 ? DEFAULT_INIT_SLEEPING_CAPACITY : init);
        _pool = new Stack();
        _pool.ensureCapacity( initcapacity > _maxSleeping ? _maxSleeping : initcapacity);
    }

    public synchronized Object borrowObject() throws Exception {
        Object obj = null;
        try {
            obj = _pool.pop();
        } catch(Exception e) {
            if(null == _factory) {
                throw new NoSuchElementException();
            } else {
                obj = _factory.makeObject();
            }
        }
        if(null != _factory && null != obj) {
            _factory.activateObject(obj);
        }
        _numActive++;
        return obj;
    }

    public void returnObject(Object obj) throws Exception {
        boolean success = true;
        if(!(_factory.validateObject(obj))) {
            success = false;
        } else {
            try {
                _factory.passivateObject(obj);
            } catch(Exception e) {
                success = false;
            }
        }

        boolean shouldDestroy = !success;

        synchronized(this) {
            _numActive--;
            if(_pool.size() >= _maxSleeping) {
                shouldDestroy = true;
            } else if(success) {
                _pool.push(obj);
            }
            notifyAll(); // _numActive has changed
        }

        if(shouldDestroy) {
            try {
                _factory.destroyObject(obj);
            } catch(Exception e) {
                // ignored
            }
        }
    }

    public int getNumIdle() {
        return _pool.size();
    }

    public int getNumActive() {
        return _numActive;
    }

    public synchronized void clear() {
        if(null != _factory) {
            Enumeration enum = _pool.elements();
            while(enum.hasMoreElements()) {
                try {
                    _factory.destroyObject(enum.nextElement());
                } catch(Exception e) {
                    // ignore error, keep destroying the rest
                }
            }
        }
        _pool.clear();
    }

    synchronized public void close() throws Exception {
        clear();
        _pool = null;
        _factory = null;
    }

    synchronized public void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
        if(0 < getNumActive()) {
            throw new IllegalStateException("Objects are already active");
        } else {
            clear();
            _factory = factory;
        }
    }

    /** The default 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. */
    protected Stack _pool = null;

    /** My {@link PoolableObjectFactory}. */
    protected PoolableObjectFactory _factory = null;

    /** The cap on the number of "sleeping" instances in the pool. */
    protected int _maxSleeping = DEFAULT_MAX_SLEEPING;

    protected int _numActive = 0;
}
