I had come across openMP, which could be used to parallelize the for loops in c, C++. Of course, OpenMP could do much more than just that. But i'm curious if we can parallelize the for loops in java to optimize the performance of the programs. Suppose i have n iterations in a for loop, is there a way to parallelly run these iterations?
If each iteration takes a lot of time and independent from previous computations in loop, then use ExecutorServiceand submit calculations as tasks.
ExecutorService executorService = Executors.newFixedThreadPool(4); // number of threads
for (int i = 0; i < n; i++) {
   // declare variables as final which will be used in method run below
   final int count = i;
   executorService.submit(new Runnable() {
       @Override
       public void run() {
           //do your long stuff and can use count variable
       }
   });
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With