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

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.aop.Advisor;
import org.jboss.aop.joinpoint.MethodInvocation;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.5.2.4 $
 */
public class ThreadPoolExecutor implements ExecutorAbstraction
{
   private static ExecutorService executor = Executors.newCachedThreadPool();

   public void setAdvisor(Advisor advisor)
   {

   }

   public RemotableFuture execute(MethodInvocation invocation) throws Exception
   {
      final MethodInvocation copy = (MethodInvocation) invocation.copy();
      final ClassLoader cl = Thread.currentThread().getContextClassLoader();
      
      java.util.concurrent.Future future = executor.submit(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);
            }
         }
      });

      return new FutureImplJavaUtilConcurrent(future);
   }

}
