gpt4 book ai didi

java - 如何以线程安全且高效的方式使用 XPath?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:19:44 25 4
gpt4 key购买 nike

(这里曾问过一个类似的问题,Java XPathFactory thread-safety,但给出的答案是不正确的,因为它忽略了文档指出 XPathFactory.newInstance() 不是线程安全的事实.)

来自XPathFactory Javadoc ,我们有:

The XPathFactory class is not thread-safe. In other words, it is the application's responsibility to ensure that at most one thread is using a XPathFactory object at any given moment. Implementations are encouraged to mark methods as synchronized to protect themselves from broken clients.

XPathFactory is not re-entrant. While one of the newInstance methods is being invoked, applications may not attempt to recursively invoke a newInstance method, even from the same thread.

所以根据上面的引述,我认为不应同时调用 XPathFactory.newInstance()(静态方法)。它不是线程安全的。

工厂返回 XPath 对象,它有这个 XPath Javadoc :

An XPath object is not thread-safe and not reentrant. In other words, it is the application's responsibility to make sure that one XPath object is not used from more than one thread at any given time, and while the evaluate method is invoked, applications may not recursively call the evaluate method.

根据上面的引述,我认为不应同时调用 XPath.evaluateXPathExpression.evaluate。它们不是线程安全的。

通常当我处理非线程安全的类时,我只使用局部变量,但因为 XPathFactory.newInstance() 不是线程安全的,而且它是一个静态方法,我不确定如何安全有效地使用它。我想我可以同步对 newInstance 的调用,但我担心性能,因为我的应用程序是一个 XML 消息路由应用程序。 (在我对 newInstance 的冒烟测试中,它需要大约 0.4 毫秒。)

我找不到任何以线程安全方式使用 Java XPath 的示例,而且我不确定我知道如何以线程安全但高效的方式使用 XPath。我还有一个限制,我需要在单例中使用 XPath(特别是 Apache Camel Processor)。

最佳答案

I take it that XPathFactory.newInstance() (a static method) should not be called concurrently. It is not thread-safe.

该文档可以有不同的解释:线程安全和可重入是不同的属性,因此 XPathFactory.newInstance() 可能是线程安全的但不可重入的。 递归 这个词似乎很关键;但是句子结构很难解析。如果不仔细检查代码,围绕任何 newInstance 调用的同步似乎是使用它们的唯一安全方法。请注意,Java 9 添加了 newDefaultInstance方法,这似乎是线程安全的。

I take it that XPath.evaluate and XPathExpression.evaluate should not be called concurrently. They are not thread-safe.

同意。文档明确指出这些方法既不是线程安全的也不是可重入的。

关于java - 如何以线程安全且高效的方式使用 XPath?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com