I read about the implementation of the Fork/Join framework that was introduced in Java 7 and I just wanted to check that I understand how the magic works.
As I understand, when a thread forks, it creates subtasks in its queue (which other thread may or may not steal). When the thread attempts to "join", it actually checks its queue for existing tasks and then recursively perform them, which mean that for any 'join' operation - 2 frames will be added into the thread call stack (one for the join and one for the new taken task invocation).
As I know that the JVM does not support tail call optimization (that may serve in this situation to remove the join method stack frame) I believe that while performing a complicated operation with a lot of forks and joins a thread may throw an StackOverflowError
.
Am I right or did they find some cool way to prevent it?
EDIT
Here is a scenario to help clarifying the question: Say (for simplicity) that we only have one thread in the forkjoin pool. At some point in time - the thread forks and then calls join. While in the join method the thread discovers that it can perform the forked task (as it found in its queue) so it invokes the next task. This task in turn forks and then call join - so while executing the join method the thread will find the forked task in its queue (like before) and invoke it. in that stage the call stack will contain at least the frames for two joins and two tasks.
as you can see the fork join framework transformed to plain recursion. Because java does not support tail call optimization - every recursion in java can cause StackOverflowError
if it goes deep enough.
My question is - did the implementer of the fork/join framework find some cool way to prevent this situation.