/* JFox, the OpenSource J2EE Application Server
*
* Copyright (C) 2002 huihoo.org
* Distributable under GNU LGPL license
* See the GNU Lesser General Public License for more details.
*/

package org.huihoo.jfox.pool.thread;

import org.huihoo.jfox.pool.ObjectPool;
import org.huihoo.jfox.pool.SimpleObjectPool;
import org.huihoo.jfox.pool.ObjectFactory;
import org.huihoo.jfox.service.ComponentSupport;

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

public class SimpleThreadPool extends ComponentSupport implements SimpleThreadPoolMBean,ThreadPool {

  /**
   * the objectPool to cache the WorkerThread object
   */
  private ObjectPool pool = null;

  public SimpleThreadPool() {
    try {
      pool = new SimpleObjectPool(new ThreadableObjectFactory(WorkerThread.class),5,10);
    }
    catch(Exception e){
      logger.fatal(e.getMessage(),e);
    }
  }

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

  protected void doInit() throws Exception {
    try {
      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();
  }

}