1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import java.lang.reflect.InvocationTargetException; import java.util.concurrent.*; public class ParallelCaller { public static final int NUM_CORES = 2 * Runtime.getRuntime().availableProcessors(); private ExecutorService eservice = Executors.newFixedThreadPool(NUM_CORES); ; private CompletionService<Object> cservice = new ExecutorCompletionService<>(eservice); public void Parallel( int numtasks, int iterations, Class clazz, Object... args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { long begTest = new java.util.Date().getTime(); for ( int index = 1 ; index <= numtasks; index++) { cservice.submit((Callable<Object>) clazz.getConstructors()[ 0 ].newInstance(args)); } eservice.shutdown(); Object taskResult; for ( int index = 0 ; index < numtasks; index++) { try { taskResult = cservice.take().get(); System.out.println( "result " + taskResult); } catch (ExecutionException e) { System.out.println(e.getMessage()); } catch (InterruptedException e) { System.out.println(e.getMessage()); // (Re-)Cancel if current thread also interrupted eservice.shutdownNow(); // Preserve interrupt status Thread.currentThread().interrupt(); } } Double secs = new Double(( new java.util.Date().getTime() - begTest) * 0.001 ); System.out.println( "run time " + secs + " secs" ); } } |
Usage:
1 2 3 4 5 6 | public static void main(String[] args) throws NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { int parallel = args.length > 0 ? Integer.parseInt(args[ 0 ]) : 5 ; int iterations = args.length > 1 ? Integer.parseInt(args[ 1 ]) : 100 ; new ParallelCaller().Parallel(parallel, iterations, LoginTest. class , "http://somethingtotest.com" , "testuser02" , "testuser02" , iterations, LoginTest.KnownDrivers.Firefox); } |