views:

167

answers:

3

Hi,

I was wondering if there is a Parallel.For equivalent to the .net version for Java?

If there is could someone please supply an example? thanks!

Jamie

+3  A: 

Fork join framework in Java 7 is for concurrency support. But I don't know about an exact equivalent for Parallel.For.

Emil
+8  A: 

I guess the closest thing would be:

ExecutorService exec = Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);
    try {
        for (Object o : list) {
            final Object obj = o;
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    // do stuff with obj.
                }
            });
        }
    } finally {
        exec.shutdown();
    }

Based on TheLQ's comments, you would set SUM_NUM_THREADS to Runtime.getRuntime().availableProcessors();

I also agree that you would probably want to make use of a countdown latch.

Decided to add a basic "Parallel.For" Concerned about the performance of newing up a thread pool every time...

public class Parallel {
    private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();
    public static <T> void For(final Iterable<T> pElements, final Operation<T> pOperation) {
        ExecutorService executor = Executors.newFixedThreadPool(NUM_CORES);
        List<Future<?>> futures = new LinkedList<Future<?>>();
        for (final T element : pElements) {
            Future<?> future = executor.submit(new Runnable() {
                @Override
                public void run() {
                    pOperation.perform(element);
                }
            });

            futures.add(future);
        }

        for (Future<?> f : futures) {
            try {
                f.get();
            } catch (InterruptedException e) {
            } catch (ExecutionException e) {
            }
        }
        executor.shutdown();
    }

    public static interface Operation<T> {
        public void perform(T pParameter);
    }
}
mlaw
+1 for a solution for current systems…
Donal Fellows
Yea, you could easily pass a Anonymous class to a method that does the work for you. Could even add a CountDownLatch and have each run() deincriment it so that you can have it block. The only issue is that you don't know the number of cores a computer has, so you can't optimize the number of threads for the cores.
TheLQ
You can have the following to drop the extra obj reference: for (final Object o : list) {
Peter Lawrey
A: 

A simpler option would be

// A thread pool which runs for the life of the application.
private static final ExecutorService EXEC = 
    Executors.newFixedThreadPool(SOME_NUM_OF_THREADS); 

//later 
EXEC.invokeAll(tasks); // you can optionally specify a timeout.
Peter Lawrey