Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallelize for loops in java

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?

like image 680
redwolf_cr7 Avatar asked Jan 14 '23 00:01

redwolf_cr7


1 Answers

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
       }
   });
}
like image 88
Tala Avatar answered Jan 16 '23 01:01

Tala