0

I'm running a simulation for several repetitions and I'm trying to see if it would be possible to parallellise these repetitions to improve computation time.

Currently I simply run the simulation several times in a for loop, but ideally these could all be run at the same time, and then the results from each repetition saved to an array for processing.

Currently my code is something like

public static void getAllTheData(){

   int nReps = 10;
   double[][] allResults = new double[nReps][]

   //this for loop is what I want to parallellise 
   for(int r = 0; r < nReps; r++){

       //run the simulation to completion here
       simulation.doStuffToCompletion()

       allResults[r] = simulation.getValues()

   }
//average allResults here and do further analysis
}

My question is, how can I run all these repetitions at the same time in parallel, and save the results from each parallel run in an allResults type array?

Thanks very much.

ponsly
  • 87
  • 9

2 Answers2

2

You can try something like parallel streams to do parallelism like one of the below lines.

Stream.of(allResults).parallel().forEach(i -> processData(i));

Arrays.stream(allResults).parallel().forEach(i -> processData(i));
Anil
  • 543
  • 3
  • 16
  • 1
    You can also consider the following to populate the result array easily: `IntStream.range(0, nReps).parallel().forEach(i -> allResults[i] = runSimulation());` – Bar Mako Feb 25 '19 at 15:05
  • It's not the analysis of allResults I'd like to parallellise, but rather the for loop above that which repeats the simulation several times in order to get the raw data. Would your method work to get the raw data, or does it only work on an array which already has values assigned to it? – ponsly Feb 25 '19 at 15:06
1

Java is a synchronous language by default and to do work in parallel you would need to look into threads. I suggest looking into asynchronous function calls and ways to do it in Java.

Here is a previous question asked on this matter: How to asynchronously call a method in Java

With an asynchronous call, you can run your simulation on however many threads you want and collect the data as your simulation runs finish.

Engin
  • 76
  • 6