Showing posts with label concurrent. Show all posts
Showing posts with label concurrent. Show all posts

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.

Java: Parallel.For

This piece is from StackOverflow:

public class Parallel {
    private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();

    private static final ExecutorService forPool = Executors.newFixedThreadPool(NUM_CORES  * 2);

    public static void For(final Iterable<T> elements, final Operation<T> operation) {
        try {
            // invokeAll blocks for us until all submitted tasks in the call complete
            forPool.invokeAll(createCallables(elements, operation));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static Collection<Callable<Void>> createCallables(final Iterable<T> elements, final Operation<T> operation) {
        List<Callable<Void>> callables = new LinkedList<Callable<Void>>();
        for (final T elem : elements) {
            callables.add(new Callable<Void>() {
                @Override
                public Void call() {
                    operation.perform(elem);
                    return null;
                }
            });
        }

        return callables;
    }

    public static interface Operation<T> {
        public void perform(T pParameter);
    }
}

Usage:
// Collection of items to process in parallel
Collection<Integer> elems = new LinkedList<Integer>();
for (int i = 0; i < 40; ++i) {
    elems.add(i);
}
Parallel.For(elems, 
 // The operation to perform with each item
 new Parallel.Operation<Integer>() {
    public void perform(Integer param) {
        System.out.println(param);
    };
});

Java: Simple multithreading a piece of code

import java.util.*;
import java.util.concurrent.*;

// ...

ExecutorService exec = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());
try {
    for (int i = 0; i < num_of_runs; i++) {
        exec.submit(new Runnable() {
            @Override
            public void run() {
                // do stuff in num_of_runs times through a 2*#CPU threadpool
            }
        });
    }
} finally {
    exec.shutdown();
}