/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.aspects.asynch;

import EDU.oswego.cs.dl.util.concurrent.Callable;
import EDU.oswego.cs.dl.util.concurrent.Executor;
import EDU.oswego.cs.dl.util.concurrent.FutureResult;
import EDU.oswego.cs.dl.util.concurrent.PooledExecutor;
import org.jboss.aop.Advisor;
import org.jboss.aop.joinpoint.MethodInvocation;

/**
 * Use a global thread pool to execute asynch tasks
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.3.2.3 $
 */
public class ThreadPoolExecutor implements ExecutorAbstraction
{
   private static Executor executor = new PooledExecutor();

   public void setAdvisor(Advisor advisor)
   {

   }

   public RemotableFuture execute(MethodInvocation invocation) throws Exception
   {
      final MethodInvocation copy = (MethodInvocation) invocation.copy();
      final ClassLoader cl = Thread.currentThread().getContextClassLoader();
      
      FutureResult result = new FutureResult();
      Runnable command = result.setter(new Callable()
      {
         public Object call() throws Exception
         {
            try
            {
               Thread.currentThread().setContextClassLoader(cl);
               return copy.invokeNext();
            }
            catch (Throwable throwable)
            {
               if (throwable instanceof Exception)
               {
                  throw ((Exception) throwable);
               }
               else
                  throw new Exception(throwable);
            }
         }
      });
      executor.execute(command);

      return new FutureImpl(result);
   }

}
