2013-08-30

Java: Running any type of Callable with any kind of constructors

Java 1.7
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:
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);
    }
The referred class should implement Callable.

No comments :

Post a Comment