简体   繁体   中英

ForkJoinTask - join() vs invoke()

Java docs says next for join() :

Returns the result of the computation when it is done. This method differs from get() in that abnormal completion results in RuntimeException or Error, not ExecutionException, and that interrupts of the calling thread do not cause the method to abruptly return by throwing InterruptedException.

And for invoke() :

Commences performing this task, awaits its completion if necessary, and returns its result, or throws an (unchecked) RuntimeException or Error if the underlying computation did so.

But even after reading docs I can't understand difference between them. Both of them waits for future to return result, as I understand they handles exceptions in different ways?

In the ForkJoinTask API docs,

The primary method for awaiting completion and extracting results of a task is join(), but there are several variants: The Future.get() methods support interruptible and/or timed waits for completion and report results using Future conventions. Method invoke() is semantically equivalent to fork(); join() but always attempts to begin execution in the current thread. The "quiet" forms of these methods do not extract results or report exceptions. These may be useful when a set of tasks are being executed, and you need to delay processing of results or exceptions until all complete. Method invokeAll (available in multiple versions) performs the most common form of parallel invocation: forking a set of tasks and joining them all.

In simple words, invoke() == fork();join();

fork() itself is asynchronous where it split the tasks two work units and passes the one unit to another ForkJoinTask, and the number of ForkJoinTask available is defined by your ForkJoinPool. And, you will call join()/get() to wait for it to complete.

Meanwhile, for invoke(), it is synchronous and the ForkJoinTask is invoke at the main thread, blocking the main thread immediately. If you need to execute something in between fork() and join() you couldn't.

So my advise is use invoke() when you have nothing to do in between fork() & join() and you just need pure multi-threading capabilities. If you want advanced joining between ForkJoinTasks or execute something in between, then use fork();join();

But keep in mind, both methods does not means that your tasks get to split into another thread. It depends on the number of physical thread in your machine and the number of pools initialized for your ForkJoinPool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM