Difference between Execute, Submit and Invoke () in ForkJoinPool

I have the following class that starts and compiles (you can try it). The only thing that puzzles me a bit is that in the end in the main it works fine with fj.invoke (task), but not with fj.execute (task) and fj.submit (task). I do not get any results with the latter. From the API, it should work with other methods, they also perform the task. Even if they either return or do not matter, they still have to complete the task. What am I missing here?

import java.util.concurrent.RecursiveAction; import java.util.concurrent.ForkJoinPool; public class RecursiveTaskActionThing extends RecursiveAction{ int roba; static int counter; public RecursiveTaskActionThing(int roba) { this.roba = roba; } public void compute() { if (roba<100) { System.out.println("The thing has been split as expected: "+ ++counter ); } else{ roba = roba/2; RecursiveTaskActionThing rc1 = new RecursiveTaskActionThing(roba); RecursiveTaskActionThing rc2 = new RecursiveTaskActionThing(roba); this.invokeAll(rc1,rc2); } } public static void main (String []args) { ForkJoinPool fj = new ForkJoinPool(); fj.invoke(new RecursiveTaskActionThing(500)); } } 

You can try this simply by copying and pasting the code, replacing

fj.invoke(new RecursiveTaskActionThing(500)); with

fj.execute(new RecursiveTaskActionThing(500)); or with

fj.submit(new RecursiveTaskActionThing(500)); he will not spit out any conclusion ... I wonder why.

Thanks in advance.

+6
source share
1 answer

Based on your last question, it would be helpful for you to learn how to read different code for specific questions like this.

But still. invoke will complete and join this task. execute and submit push the task to the work queue, which will be worked on later. If you want the expected output to call the join method of the task after submit ing or execute ing.

Now, when the last question should be: "Why this task will not be launched at all?" Threads are created as setDaemon(true) , so when you leave your main method, you die the main Thread. And since the specification indicates when only daemon threads are running, the system will exit.

By joining a task, you pause the main thread until the fork merge tasks are completed.

+7
source

Source: https://habr.com/ru/post/950350/


All Articles