Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XPathFactory thread-safety

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?

like image 333
Alex Ciminian Avatar asked Feb 02 '12 10:02

Alex Ciminian


1 Answers

"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.

like image 88
bmadigan Avatar answered Sep 19 '22 00:09

bmadigan