2013-08-30

Java: Parallel.For

This piece is from StackOverflow:

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
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:
1
2
3
4
5
6
7
8
9
10
11
12
// 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);
    };
});

No comments :

Post a Comment