DocumentBuilderFactory在Java 5中线程安全吗?

javax.xml.parsers.DocumentBuilderFactory的Java 1.4 doc没有明确的规定:

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.

然而,Java 5Java 6文档没有说什么.现在DocumentBuilderFactory线程安全了,还是Sun刚刚决定警告是否过度,人们应该知道更好?

最佳答案
DocumentBuilderFactory类的实现不能保证线程安全.用户应用程序可以确保使用多个线程的DocumentBuilderFactory.或者,应用程序可以在每个线程上具有DocumentBuilderFactory的一个实例.一个应用程序可以使用相同的工厂实例来获取DocumentBuilder的一个或多个实例,只要工厂的实例一次不被多个线程使用.

在DocumentBuilder上有一个reset()方法,它将其恢复到首次创建时的状态.如果你要去ThreadLocal路线,不要忘了打电话给你,或者你很沮丧.

转载注明原文:DocumentBuilderFactory在Java 5中线程安全吗? - 代码日志