DocumentBuilder.parse()线程安全吗?

Avi*_*Avi 26 java thread-safety

标准的Java 1.6 javax.xml.parsers.DocumentBuilder类是否安全?从多个线程并行调用parse()方法是否安全?

JavaDoc没有提到这个问题,但Java 1.4中同一类JavaDoc明确表示它并不意味着并发; 所以我可以假设在1.6中它是?

原因是我在ExecutorService中运行了数百万个任务,每次调用DocumentBuilderFactory.newDocumentBuilder()似乎都很昂贵.

Tom*_*ine 26

即使DocumentBuilder.parse看起来不会改变它在Sun JDK默认实现(基于Apache Xerces)上的构建器.偏心的设计决定.你能做什么?我想使用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);
            }
        }
    };
Run Code Online (Sandbox Code Playgroud)

(免责声明:与尝试编译代码不同.)


Tre*_*ton 19

DocumentBuilder上有一个reset()方法,它将其恢复到首次创建时的状态.如果您正在使用ThreadLocal路线,请不要忘记给它打电话或者你已经开了.