If I have a parallel stream in java 8, and I terminate with an anyMatch, and my collection has an element that matches the predicate, I\'m trying to figure out what happens
After some digging through the Java source code I think I found the answer.
The other threads periodically check to see if another thread has found the answer and if so, then they stop working and cancel any not yet running nodes.
java.util.Stream.FindOps$FindTask
has this method:
private void foundResult(O answer) {
if (isLeftmostNode())
shortCircuit(answer);
else
cancelLaterNodes();
}
Its parent class, AbstractShortcircuitTask
implements shortCircuit
like this:
/**
* Declares that a globally valid result has been found. If another task has
* not already found the answer, the result is installed in
* {@code sharedResult}. The {@code compute()} method will check
* {@code sharedResult} before proceeding with computation, so this causes
* the computation to terminate early.
*
* @param result the result found
*/
protected void shortCircuit(R result) {
if (result != null)
sharedResult.compareAndSet(null, result);
}
And the actual compute()
method that does the work has this important line:
AtomicReference<R> sr = sharedResult;
R result;
while ((result = sr.get()) == null) {
...//does the actual fork stuff here
}
where sharedResult
is updated by the shortCircuit()
method so the compute will see it the next time it checks the while loop condition.
EDIT So in summary: