java-8 – Java 8并行流anyMatch – 一旦找到匹配,线程会中断?
如果我在
java 8中有并行流,并且我终止了一个anyMatch,并且我的集合有一个与谓词匹配的元素,我试图找出当一个线程处理这个元素时会发生什么.
我知道anyMatch是短路的,所以我不希望在处理匹配元素后再处理更多的元素.我的混淆是关于其他线程发生的事情,大概在处理元素的中间.我可以想到3个合理的场景: 我有一个长时间运行的谓词,一旦我知道一个元素匹配,它很快就终止了.我担心一点,因为我在文档中找不到这个信息,它可能是实现依赖的事情,这也是很好的知道. 谢谢 解决方法
经过
Java源代码的挖掘,我觉得我找到了答案.
其他线程会定期检查另一个线程是否找到答案,如果是,则它们停止工作并取消任何尚未运行的节点. java.util.Stream.FindOps $FindTask有这个方法: private void foundResult(O answer) { if (isLeftmostNode()) shortCircuit(answer); else cancelLaterNodes(); } 它的父类AbstractShortcircuitTask这样实现shortCircuit: /** * 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); } 而实际执行的compute()方法有这个重要的一行: AtomicReference<R> sr = sharedResult; R result; while ((result = sr.get()) == null) { ...//does the actual fork stuff here } 其中sharedResult由shortCircuit()方法更新,所以计算将在下次检查while循环条件时看到它. 编辑 >线程不会中断相反,他们会定期检查是否有人找到答案,如果已经找到答案,将会停止进一步处理.>一旦找到答案,就不会启动新的主题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |