Java 5+ 中的 DocumentBuilderFactory 线程安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9828254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 08:14:45  来源:igfitidea点击:

Is DocumentBuilderFactory thread-safe in Java 5+?

javamultithreadingjaxp

提问by David Moles

The Java 1.4 docfor javax.xml.parsers.DocumentBuilderFactorystates in no uncertain terms:

Java 1.4的文档用于javax.xml.parsers.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. Alternatively the application can have one instance of the DocumentBuilderFactory per thread. An application can use the same instance of the factory to obtain one or more instances of the DocumentBuilder provided the instance of the factory isn't being used in more than one thread at a time.

DocumentBuilderFactory 类的实现不能保证是线程安全的。由用户应用程序来确保从多个线程使用 DocumentBuilderFactory。或者,应用程序可以为每个线程拥有一个 DocumentBuilderFactory 实例。应用程序可以使用工厂的同一个实例来获取 DocumentBuilder 的一个或多个实例,前提是工厂的实例一次没有在多个线程中使用。

The Java 5and Java 6docs, however, say nothing of the kind. Is DocumentBuilderFactorythread-safe now, or did Sun just decide the warning was overkill and people should know better?

Java 5的Java 6的文档,但是,说什么的那种。DocumentBuilderFactory现在是线程安全的,还是 Sun 只是认为警告是矫枉过正,人们应该更清楚?

回答by Pavel Rozenblioum

Since it would've been in extremely poor taste to make it thread safe without telling my money is that it's still unsafe. You can test this yourself using breakpoints.

因为在不告诉我的钱它仍然不安全的情况下使其线程安全是非常糟糕的品味。您可以使用断点自行测试。

回答by bdzzaid

According to the documentation of the singleton DocumentBuilderFactorythe newInstancemethod is not sychronizedand then, the DocumentBuilderFactory is still not a thread safe in Java 8... Neither in Java 11. Actually, the constructor didn't change since Java 1.4.

根据单例DocumentBuilderFactory 的文档newInstance方法未同步,然后 DocumentBuilderFactory 在 Java 8 中仍然不是线程安全的......在Java 11 中也不是。实际上,构造函数从 Java 1.4 开始就没有改变。