1package org.testng.internal.thread;
2
3
4import java.util.List;
5import java.util.concurrent.LinkedBlockingQueue;
6import java.util.concurrent.ThreadFactory;
7import java.util.concurrent.ThreadPoolExecutor;
8import java.util.concurrent.TimeUnit;
9
10/**
11 * An implementation for <code>IExecutor</code> based on <code>ThreadPoolExecutor</code>
12 *
13 * @author <a href="mailto:the_mindstorm@evolva.ro>Alexandru Popescu</a>
14 */
15public class ExecutorAdapter extends ThreadPoolExecutor implements IExecutor {
16  private IThreadFactory m_threadFactory;
17
18  public ExecutorAdapter(int threadCount, IThreadFactory tf) {
19      super(threadCount,
20            threadCount,
21            0L,
22            TimeUnit.MILLISECONDS,
23            new LinkedBlockingQueue<Runnable>(),
24            (ThreadFactory) tf.getThreadFactory());
25      m_threadFactory = tf;
26   }
27
28   @Override
29  public IFutureResult submitRunnable(final Runnable runnable) {
30      return new FutureResultAdapter(super.submit(runnable));
31   }
32
33   @Override
34  public void stopNow() {
35      super.shutdownNow();
36   }
37
38   @Override
39  public boolean awaitTermination(long timeout) {
40     boolean result= false;
41     try {
42      result= super.awaitTermination(timeout, TimeUnit.MILLISECONDS);
43     }
44     catch(InterruptedException handled) {
45       System.out.println("[WARN] ThreadPoolExecutor has been interrupted while awaiting termination");
46       Thread.currentThread().interrupt();
47     }
48
49     return result;
50   }
51
52  @Override
53  public StackTraceElement[][] getStackTraces() {
54    List<Thread> threads = m_threadFactory.getThreads();
55    int threadCount = threads.size();
56    StackTraceElement[][] result = new StackTraceElement[threadCount][];
57    for (int i = 0; i < result.length; i++) {
58      result[i] = threads.get(i).getStackTrace();
59    }
60    return result;
61  }
62}