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?
"One of them is that XPathFactory.newInstance() is very expensive;"
True statement! I noticed that for each thread calling newInstance(), jaxp.properties must be located on the classpath and read in:
java.lang.Thread.State: BLOCKED (on object monitor)
at java.util.zip.ZipFile.getEntry(ZipFile.java:160)
- locked <0x0000000968dec028> (a sun.net.www.protocol.jar.URLJarFile)
at java.util.jar.JarFile.getEntry(JarFile.java:208)
at sun.net.www.protocol.jar.URLJarFile.getEntry(URLJarFile.java:107)
at sun.net.www.protocol.jar.JarURLConnection.connect(JarURLConnection.java:114)
at sun.net.www.protocol.jar.JarURLConnection.getInputStream(JarURLConnection.java:132)
at java.net.URL.openStream(URL.java:1010)
at javax.xml.xpath.SecuritySupport$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at javax.xml.xpath.SecuritySupport.getURLInputStream(Unknown Source)
at javax.xml.xpath.XPathFactoryFinder._newFactory(Unknown Source)
at javax.xml.xpath.XPathFactoryFinder.newFactory(Unknown Source)
at javax.xml.xpath.XPathFactory.newInstance(Unknown Source)
at javax.xml.xpath.XPathFactory.newInstance(Unknown Source)
ZipFile makes a native call (to zlib I believe) and decompresses the jar, which needs disk IO and processor bound zip decompression. In this instance we had 1400+ threads waiting on that lock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With