The Java 1.4 doc for javax.xml.parsers.DocumentBuilderFactory
states in no uncertain terms:
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.
The Java 5 and Java 6 docs, however, say nothing of the kind. Is DocumentBuilderFactory
thread-safe now, or did Sun just decide the warning was overkill and people should know better?
I haven't actually looked at this in some time, but looking at the source for DocumentBuilderFactoryImpl
and DocumentBuilderImpl
it looks to me like it's probably a bad idea. The factory has a bunch of internal state, and the builder modifies that state during its construction -- see the call to setDocumentBuilderFactoryAttributes
in the DocumentBuilderImpl
constructor.
If you knew you were never going to pass in those attributes, you might be able to get away with it, but to be safe I'd want to wrap the whole thing in some other object that doesn't expose the dangerous bits, and I think it would be easier just to make sure you have a separate factory per thread.