is there a way to know if a parallel foreach on a concurrent hashmap has ended
here is an example of what I want to do:
import java.util.concurrent.ConcurrentHashMap;
import java.util.Random;
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
var mainMap = new ConcurrentHashMap<Integer, String>();
Random rnd = new Random();
//I don't know from the beginning how many objects
for(int i=0; i<rnd.nextInt(100); i++){
mainMap.put(i,"elem "+i);
}
mainMap.forEach(1, (k, v) -> {
//this modelize a sub-task my application executes asynchronously
Thread t = new Thread(()->{
System.out.println("Object "+k+" started working <" + v+">");
try {
Thread.sleep(k*500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Object "+k+" done after "+(k*500)+" ms");
});
t.start();
});
//I want to print this only after all jobs are finished
//but still I don't want to block the main (GUI) thread
System.out.println("All job done !");
return;
}
}
right now an output is like this:
Hello World
All job done !
Object 0 started working <elem 0>
Object 2 started working <elem 2>
Object 4 started working <elem 4>
Object 3 started working <elem 3>
Object 1 started working <elem 1>
Object 0 done after 0 ms
Object 1 done after 500 ms
Object 2 done after 1000 ms
Object 3 done after 1500 ms
But I expect something like this:
Hello World
Object 0 started working <elem 0>
Object 2 started working <elem 2>
Object 4 started working <elem 4>
Object 3 started working <elem 3>
Object 1 started working <elem 1>
Object 0 done after 0 ms
Object 4 done after 2000 ms
Object 1 done after 500 ms
Object 2 done after 1000 ms
Object 3 done after 1500 ms
All job done !
A simple way to do that is to collect all the Threads into a list, then
joineach of them (in a separateThread, so you don't block the main thread)But I don't think your strategy of an unlimited number of threads is good -- usually there is an optimal degree of parallelism, depending on the number of processors and the amount of IO each thread performs.
I think it's better to use a thread pool: