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

import org.jboss.system.ServiceMBeanSupport;

/** 
 * Server Side MultiThread TM test.
 * 
 * Based on mbean.TMTest
 *
 * @author <a href="dimitris@jboss.org">Dimitris Andreadis</a>
 * @version $Revision: 1.2.2.2 $
 */
public class MTTest extends ServiceMBeanSupport
   implements MTTestMBean
{
   public void testMTOperations(String test, MTOperation[][] ops) throws Exception
   {
      log.info("*** Starting test: " + test);
      MTOperation.init(log);
      
      // find out how many MTOperation[]
      // we'll execute each in a separate thread
      int numOfThreads = ops.length;
      log.info("Number of Threads: " + numOfThreads);
         
      Thread[] threads = new Thread[numOfThreads];
      ExecTask[] tasks = new ExecTask[numOfThreads];
      for (int i = 0; i < numOfThreads; i++)
      {
         tasks[i] = new ExecTask(i, ops[i]);
         threads[i] = new Thread(tasks[i]);
         threads[i].start();
      }
      
      // join the threads before returning and check
      // if any of threads exited with an exception
      Exception caughtException = null;
      for (int i = 0; i < numOfThreads; i++)
      {
         try
         {
            threads[i].join();
            if (tasks[i].exception != null)
            {
               // remember any exception caught; order here is not important,
               // since we don't know which thread finished first.
               caughtException = tasks[i].exception;
            }
         }
         catch (InterruptedException e)
         {
            // retry
            i--;
         }
      }
      log.info("*** Finished test: " + test);
      MTOperation.destroy();
      
      if (caughtException != null)
      {
         throw caughtException;
      }
   }
   
   private class ExecTask implements Runnable
   {
      int threadId;
      MTOperation[] ops;
      Exception exception;
      
      public ExecTask(int threadId, MTOperation[] ops)
      {
         this.threadId = threadId;
         this.ops = ops;
      }
      
      public void run()
      {
         log.info("Starting thread: " + Thread.currentThread().getName());
         try
         {
            for (int i = 0; i < ops.length; ++i)
            {
               ops[i].perform();
            }
         }
         catch (Exception e)
         {
            exception = e;
         }
         finally
         {
            log.info("Finished thread: " + Thread.currentThread().getName());
         }
      }
   }
}
