Is javax.xml.XPathFactory.newInstance() thread-safe?
I’m asking because I find the documentation ambiguous for it. The JDK 5 docs don’t mention thread-safety at all; in JDK 6 they wrote the following:
The XPathFactory class is not thread-safe. In other words, it is the
application’s responsibility to ensure that at most one thread is
using a XPathFactory object at any given moment. Implementations are
encouraged to mark methods as synchronized to protect themselves from
broken clients.
As I understand it, it’s not safe to have a singleton implementation for XPathFactory, but doing something like this should be safe:
XPath xPathEvaluator = XPathFactory.newInstance().newXPath();
Am I missing something? Does it depend on the actual class that extends it? Do I need to synchronize the method that contains the above statement?
That is safe, because every thread gets its own factory (thanks to
newInstance()). No need to synchronize here.What you cannot safely do is get the factory just once, and then share it between threads without synchronization, for example as a singleton. The same goes for the XPath instance (
xPathEvaluator) itself.