All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.testng.internal.PoolService Maven / Gradle / Ivy

There is a newer version: 7.10.1
Show newest version
package org.testng.internal;

import java.util.concurrent.atomic.AtomicInteger;
import org.testng.TestNGException;
import org.testng.collections.Lists;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import org.testng.internal.thread.ThreadUtil;

/**
 * Simple wrapper for an ExecutorCompletionService.
 */
public class PoolService {

  private final ExecutorCompletionService m_completionService;
  private final ExecutorService m_executor;

  public PoolService(int threadPoolSize) {

    ThreadFactory threadFactory = new ThreadFactory() {

      private final AtomicInteger threadNumber = new AtomicInteger(0);

      @Override
      public Thread newThread(Runnable r) {
        return new Thread(r,
            ThreadUtil.THREAD_NAME + "-PoolService-" + threadNumber.getAndIncrement());
      }
    };
    m_executor = Executors.newFixedThreadPool(threadPoolSize, threadFactory);
    m_completionService = new ExecutorCompletionService<>(m_executor);
  }

  public List submitTasksAndWait(List> tasks) {

    List> takes = Lists.newArrayList(tasks.size());
    for (Callable callable : tasks) {
      takes.add(m_completionService.submit(callable));
    }

    List result = Lists.newArrayList(takes.size());
    for (Future take : takes) {
      try {
        result.add(take.get());
      } catch (InterruptedException | ExecutionException e) {
        throw new TestNGException(e);
      }
    }

    m_executor.shutdown();
    return result;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy