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
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
Fork join framework in Java 7 is for concurrency support. But I don't know about an exact equivalent for Parallel.For
.
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);
}
}
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.