/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.pool.thread;

import org.jfox.pool.AbstractObjectPool;
import org.jfox.pool.ObjectFactory;
import org.jfox.pool.PoolableObject;
import org.jfox.pool.SimpleObjectPool;
import org.jfox.system.AbstractComponent;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class SimpleThreadPool extends AbstractComponent implements ThreadPool {

    /**
     * the objectPool to cache the PoolableThreadImpl object
     */
    private AbstractObjectPool pool = null;

    public SimpleThreadPool() {

    }

    public void execute(Threadable task) {
        try {
            ThreadTask threadTask = new ThreadTask(task, pool);
            ((PoolableThread) pool.retrieveObject()).setTask(threadTask);
        }
        catch(Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    protected void doInit() throws Exception {
        try {
            pool = new SimpleObjectPool(new ThreadObjectFactory(PoolableThreadImpl.class), 5, 10);
            pool.init();
        }
        catch(Exception e) {
            logger.fatal("object pool instantiator error", e);
//      e.printStackTrace();
        }
    }

    protected void doDestroy() throws Exception {
        pool.destroy();
    }

    public void clear() {
        pool.clear();
    }

    public ObjectFactory getObjectFactory() {
        return pool.getObjectFactory();
    }

    public String getObjectClass() {
        return pool.getObjectClass();
    }

    public int getWorking() {
        return pool.getWorking();
    }

    public int getRest() {
        return pool.getRest();
    }

    public PoolableObject retrieveObject() throws Exception {
        return pool.retrieveObject();
    }

    public boolean restoreObject(PoolableObject obj) {
        return pool.restoreObject(obj);
    }

    public boolean removeObject(PoolableObject obj) {
        return pool.removeObject(obj);
    }

}