从多个线程使用 jsoup someDocument.select(..)
是否安全,或者是否有一些用于读取 操作的内部状态?
最佳答案
您可以安全地调用Document.select(String cssSelector)
来自多个线程,即使 Document
类不是线程安全的。 .select(String cssSelector)
方法的底层实现将引用传递给调用此方法的元素(在本例中为 Document
对象),但它不会调用任何更改的方法调用者的状态。
当您调用 .select(String cssSelector)
时,您实际上调用了 Collector.collect(Evaluator eval, Element root)
方法,其中 root
实例是对 Document
对象的引用。
/**
Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator.
@param eval Evaluator to test elements against
@param root root of tree to descend
@return list of matches; empty if none
*/
public static Elements collect (Evaluator eval, Element root) {
Elements elements = new Elements();
new NodeTraversor(new Accumulator(root, elements, eval)).traverse(root);
return elements;
}
在这个方法中只有 elements
对象被更新。
为什么 Document
类不是线程安全的?
Document
类中有一些方法允许在没有任何同步机制的情况下更改对象的状态,例如Document.outputSettings(Document.OutputSettings outputSettings)
.在最好的情况下,Document
类应该是最终的且不可变的,因此在多个线程之间共享其实例不会成为问题。
关于java - jsoup 文档线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46407118/