gpt4 book ai didi

Java 和 XML (JAXP) - 缓存和线程安全怎么样?

转载 作者:IT老高 更新时间:2023-10-28 21:19:28 32 4
gpt4 key购买 nike

  1. 我想知道在使用Java API for XML处理时,哪些对象可以被重用(在相同或不同的文档中),JAXP:

    • DocumentBuilderFactory
    • DocumentBuilder
    • XPath
    • 节点
    • ErrorHandler (编辑:我忘了这必须在我自己的代码中实现,抱歉)
  2. 建议缓存这些对象还是 JAXP 实现已经缓存它们?

  3. 这些对象的(再)使用是否线程安全

最佳答案

重复使用

在同一个线程中,这些对象可以并且应该被重用。例如,您可以使用 DocumentBuilder 来解析多个文档。

线程安全

DocumentBuilderFactory 曾经明确表示它不是线程安全的,我相信这仍然是正确的:

An implementation of the DocumentBuilderFactory class is NOT guaranteed to be thread safe. It is up to the user application to make sure about the use of the DocumentBuilderFactory from more than one thread.

从 Stack Overflow 来看,DocumentBuilder 似乎也不是线程安全的。但是在 Java SE 5 中添加了一个重置​​方法以允许您重用 DocumentBuilder:

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.

节点不是线程安全的,来自 Xerces 网站

Is Xerces DOM implementation thread-safe? No. DOM does not require implementations to be thread safe. If you need to access the DOM from multiple threads, you are required to add the appropriate locks to your application code.

ErrorHandler 是一个接口(interface),因此由您对该接口(interface)的实现来确保线程安全。有关线程安全的指针,您可以从这里开始:

关于Java 和 XML (JAXP) - 缓存和线程安全怎么样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3439485/

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