Java 8 parallel stream + anyMatch - do threads get interrupted once a match is found?

前端 未结 1 1352
-上瘾入骨i
-上瘾入骨i 2020-12-28 18:16

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

相关标签:
1条回答
  • 2020-12-28 18:23

    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:

    1. Threads are not interrupted
    2. Instead, they will periodically check to see if someone has found the answer and will stop further processing if the answer has been found.
    3. No new threads will be started once the answer has been found.
    0 讨论(0)
提交回复
热议问题