I have 1 parallel processing code using ForkJoinPool:
ForkJoinPool customThreadPool = new ForkJoinPool(4);
customThreadPool.submit(() -> {
list.parallelStream().forEach(this::process);
});
I am invoking this though some controller. This code runs asynchronously so, controller response will be immediate and async process will happen in background.
Now I want to trigger some another processing once above all the process completes. Is there any way or method which executes only after completing ForkJoinPool submit.
I tried submit.isDone and submit.isCompletedNormally but this runs immediate not after completion of submit.
CodePudding user response:
The submit
method returns a Future
which you need to wait on. So you call get
on it. I think some code like this will work in your case
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
class Scratch {
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<String> list = List.of("a", "b", "c");
ForkJoinPool customThreadPool = new ForkJoinPool(4);
customThreadPool.submit(() -> {
list.parallelStream().forEach(Scratch::process);
}).get();
customThreadPool.submit(() -> System.out.println("done"));
}
private static void process(String s) {
System.out.println(s);
}
}
It prints
b
a
c
done
Note the order of a, b, c is not deterministic but done will always be last