Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Parallel.For" for Java?

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!

like image 960
Jamie Avatar asked Oct 24 '10 20:10

Jamie


People also ask

What is parallel in Java?

Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any java code has one stream of processing, where it is executed sequentially.

Is foreach parallel Java?

parallel foreach() Works on multithreading concept: The only difference between stream(). forEach() and parallel foreach() is the multithreading feature given in the parallel forEach(). This is way faster that foreach() and stream.

How do you run a parallel method in Java?

Do something like this: For each method, create a Callable object that wraps that method. Create an Executor (a fixed thread pool executor should be fine). Put all your Callables in a list and invoke them with the Executor.

Does Java support parallelism?

Does Java have support for multicore processors/parallel processing? Yes. It also has been a platform for other programming languages where the implementation added a "true multithreading" or "real threading" selling point.


2 Answers

I guess the closest thing would be:

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

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

Edit: Decided to add a basic "Parallel.For" implementation

public class Parallel {     private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();      private static final ExecutorService forPool = Executors.newFixedThreadPool(NUM_CORES * 2, new NamedThreadFactory("Parallel.For"));      public static <T> 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 <T> 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);     } } 

Example Usage of Parallel.For

// 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);     }; }); 

I guess this implementation is really more similar to Parallel.ForEach

Edit I put this up on GitHub if anyone is interested. Parallel For on GitHub

like image 187
Matt Wonlaw Avatar answered Sep 21 '22 22:09

Matt Wonlaw


MLaw's solution is a very practical Parallel.ForEach. I added a bit modification to make a Parallel.For.

public class Parallel { static final int iCPU = Runtime.getRuntime().availableProcessors();  public static <T> void ForEach(Iterable <T> parameters,                    final LoopBody<T> loopBody) {     ExecutorService executor = Executors.newFixedThreadPool(iCPU);     List<Future<?>> futures  = new LinkedList<Future<?>>();      for (final T param : parameters)     {         Future<?> future = executor.submit(new Runnable()         {             public void run() { loopBody.run(param); }         });          futures.add(future);     }      for (Future<?> f : futures)     {         try   { f.get(); }         catch (InterruptedException e) { }          catch (ExecutionException   e) { }              }      executor.shutdown();      }  public static void For(int start,                    int stop,                final LoopBody<Integer> loopBody) {     ExecutorService executor = Executors.newFixedThreadPool(iCPU);     List<Future<?>> futures  = new LinkedList<Future<?>>();      for (int i=start; i<stop; i++)     {         final Integer k = i;         Future<?> future = executor.submit(new Runnable()         {             public void run() { loopBody.run(k); }         });              futures.add(future);     }      for (Future<?> f : futures)     {         try   { f.get(); }         catch (InterruptedException e) { }          catch (ExecutionException   e) { }              }      executor.shutdown();      } }  public interface LoopBody <T> {     void run(T i); }  public class ParallelTest { int k;    public ParallelTest() {     k = 0;     Parallel.For(0, 10, new LoopBody <Integer>()     {         public void run(Integer i)         {             k += i;             System.out.println(i);                   }     });     System.out.println("Sum = "+ k); }  public static void main(String [] argv) {     ParallelTest test = new ParallelTest(); } } 
like image 36
Weimin Xiao Avatar answered Sep 21 '22 22:09

Weimin Xiao