Is DocumentBuilder.parse() thread safe?

前端 未结 3 1150
盖世英雄少女心
盖世英雄少女心 2020-12-28 14:03

Is the standard Java 1.6 javax.xml.parsers.DocumentBuilder class thread safe? Is it safe to call the parse() method from several threads in parallel?

The JavaDoc doe

相关标签:
3条回答
  • 2020-12-28 14:46

    Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:

    private static final ThreadLocal<DocumentBuilder> builderLocal =
        new ThreadLocal<DocumentBuilder>() {
            @Override protected DocumentBuilder initialValue() {
                try {
                    return
                        DocumentBuilderFactory
                            .newInstance(
                                "xx.MyDocumentBuilderFactory",
                                getClass().getClassLoader()
                            ).newDocumentBuilder();
                } catch (ParserConfigurationException exc) {
                    throw new IllegalArgumentException(exc);
                }
            }
        };
    

    (Disclaimer: Not so much as attempted to compile the code.)

    0 讨论(0)
  • 2020-12-28 14:58

    You can also check this code to make further optimization https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java

    0 讨论(0)
  • 2020-12-28 15:05

    There's a reset() method on DocumentBuilder which restores it to the state when it was first created. If you're going the ThreadLocal route, don't forget to call this or you're hosed.

    0 讨论(0)
提交回复
热议问题