Is it necessary that I use join()
with fork()
or I may use also either of join()
, get()
, invoke()
.
I checked the API and besides that get()
throws InterruptedException
and ExecutionException
I don't see differences... And invoke()
seems totally the same.
However I have always seen related fork()
with join()
rather than the other two methods... don't they provide parallelism? What's the purpose of having invoke()
and join()
totally the same? I can understand get() got by implementing future, however what about invoke() and join(). Thanks in advance.
EDIT: My bad in the API i quoted actually it says something about it as the already received answers pointed out. However what do they mean with:
Method invoke() is semantically equivalent to fork(); join() but always attempts to begin execution in the current thread
Thanks in advance.
Why don't you read the documentation that you linked to?
Seems pretty clear to me, awaits its completion if necessary is rather unambiguously saying that this method is not asynchronous.
This method is inherited from
Future
, this method is analogous tojoin
. From the javadoc forjoin
:So, to use the Fork/Join framework you need to call
fork
which is asynchronous. Then do the other part of the task locally. Then calljoin
.The basic premise of the fork join framework is that it is used in divide and conquer algorithms that can be multi threaded.
The idea is that you split you task into two discrete units and then pass one off to another
ForkJoinTask
viafork
- this runs concurrently to the currentThread
. You then process the other unit in the currentThread
. When you are done you calljoin
on the first task to ensure that you get the result from it.Calling
invoke
waits for the invoked task to complete. So your method in now not asynchronous. You just run all of your parts sequentially somewhat defeating the point of fork/join.So if you were to call
x.fork().join()
it would be the same asx.invoke()
but the whole point is that you do work on the currentThread
between invokingfork
andjoin
.It is written in the API doc you cited: