DocumentBuilder.parse()线程安全吗? [英] Is DocumentBuilder.parse() thread safe?

查看:85
本文介绍了DocumentBuilder.parse()线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

JavaDoc没有提及该问题,但是 Java 1.4中针对同一类的JavaDoc 特别指出,它不是意味着是并发的.所以我可以假设在1.6中是吗?

The JavaDoc doesn't mention the issue, but the JavaDoc for the same class in Java 1.4 specifically says that it isn't meant to be concurrent; so can I assume that in 1.6 it is?

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

The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.

推荐答案

即使DocumentBuilder.parse似乎没有改变它在Sun JDK默认实现(基于Apache Xerces)上所做的构建器.偏心的设计决策.你能做什么?我想使用ThreadLocal:

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.)

这篇关于DocumentBuilder.parse()线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆