gpt4 book ai didi

Java XPathFactory 线程安全

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:56 24 4
gpt4 key购买 nike

javax.xml.XPathFactory.newInstance() 是线程安全的吗?

我问这个问题是因为我发现它的文档含糊不清。 The JDK 5 docs根本不提线程安全;在 JDK 6他们写了以下内容:

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 的单例实现是不安全的,但是像这样做应该是安全的:

XPath xPathEvaluator = XPathFactory.newInstance().newXPath();

我错过了什么吗?它是否取决于扩展它的实际类?我是否需要同步包含上述语句的方法?

最佳答案

XPath xPathEvaluator = XPathFactory.newInstance().newXPath();

这是安全的,因为每个线程都有自己的工厂(感谢 newInstance())。此处无需同步。

你不能安全地做的是只获取一次工厂,然后在没有同步的情况下在线程之间共享它,例如作为一个单例。 XPath 实例 (xPathEvaluator) 本身也是如此。

关于Java XPathFactory 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9110514/

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