Search code examples
javamultithreadingforkjoinpool

How to correctly synchronize and reuse the ForkJoinPool in Java?


This is a example:

ForkJoinPool pool = new ForkJoinPool();  
pool.submit(new RecursiveTaskA());  
// wait the task to finish  
doSomethingElse();  

pool.submit(new RecursiveTaskB());
...  

Question 1:
How to ensure the RecursiveTaskA is finished before calling doSomethingElse()?
Currently my solution is:

ForkJoinPool pool = new ForkJoinPool();  
pool.submit(new RecursiveTaskA());  

pool.shutdown();  
pool.awaitTermination(1, TimeUnit.MINUTES);  

// wait the task to finish  
doSomethingElse();  

Is this the correct way? Or is there a better way?
Question 2:
If I use the solution above, then pool.submit(new RecursiveTaskB()); result errors. I don't want to make a new ForkJoinPool, how to do it?

Any link, reference would be helpful to me, thanks.


Solution

  • If I undertand your problem correctly, you can just join the submitted task:

    RecursiveTaskA taskA = new RecursiveTaskA();
    pool.submit(taskA);
    taskA.join();
    doSomethingElse();