I have a for loop which I am trying to parallelize using CompletableFuture.
for (int i = 0; i < 10000; i++) {
doSomething();
doSomethingElse();
}
What I have till now is:
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
I guess this serves the purpose but there is a requirement to print log just before the start and end of all the processing. If I do this:
log("Started doing things");
for (int i = 0; i < 10000; i++) {
CompletableFuture.runAsync(() -> doSomething());
CompletableFuture.runAsync(() -> doSomethingElse());
}
log("Ended doing things");
Does this guarantee that the second log statement will be printed once all the for loop is over since that is executing in a separate thread? If not, is there a way to do this without blocking the main thread?
CompletableFuture? (It doesn't seem you use these objects outside the loop any more, so there is no need of doing it withCompletableFutures.) - isnot2badCompletableFuture. There are other mechanisms in Java that are better suited for this purpose. - isnot2bad