Java 和 XML (JAXP) - 缓存和线程安全怎么样?
我想知道在使用 Java API for XML 处理、JAXP 时哪些对象可以重用(在相同或不同的文档中):
DocumentBuilderFactory
文档生成器
XPath
节点
(编辑:我忘记这必须在我自己的代码中实现,抱歉)ErrorHandler
是否建议缓存这些对象,或者 JAXP 实现是否已经缓存它们?
这些对象的(重新)使用是否线程安全?
I'd like to know which objects can be reused (in the same or different document) when using the Java API for XML processing, JAXP:
DocumentBuilderFactory
DocumentBuilder
XPath
Node
(EDIT: I forgot that this has to be implemented in my own code, sorry)ErrorHandler
Is it recommended to cache those objects or do the JAXP implementations already cache them?
Is the (re)use of those objects thread-safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重用
在同一个线程中,这些对象可以而且应该重用。例如,您可以使用 DocumentBuilder 来解析多个文档。
线程安全
DocumentBuilderFactory曾经明确声明它不是线程安全的,我相信这仍然是正确的:
从 Stack Overflow 来看,DocumentBuilder 似乎也不是线程安全的。然而,在 Java SE 5 中添加了重置方法,以允许您重用 DocumentBuilder:
XPath 不是线程安全的,来自 Javadoc
节点不是线程安全的,来自 Xerces 网站
ErrorHandler 是一个接口,因此由您实现该接口来确保线程安全。有关线程安全的指导,您可以从这里开始:
Reuse
In the same thread those objects can and should be reused. For example you can use the DocumentBuilder to parse multiple documents.
Thread Safety
DocumentBuilderFactory used to explicity state it was not thread safe, I believe this is still true:
From Stack Overflow, DocumentBuilder does not appear to be thread safe either. However in Java SE 5 a reset method was added to allow you to reuse DocumentBuilders:
XPath is not thread safe, from the Javadoc
Node is not thread safe, from Xerces website
ErrorHandler is an interface, so it is up to your implementation of that interface to ensure thread-safety. For pointers on thread-safety you could start here: