Java XPathFactory Security

Is javax.xml.XPathFactory.newInstance () thread safe?

I ask because I find the documentation ambiguous for her. JDK 5 documents do not mention thread safety; in JDK 6 they wrote the following:

The XPathFactory class is not thread safe. In other words, it is the responsibility of the application to ensure that no more than one thread is using the XPathFactory object at any time. Implementations are advised to note methods synchronized to protect against broken clients.

As I understand it, XPathFactory unsafe for XPathFactory have a singleton implementation, 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 method containing the above statement?

+7
source share
2 answers

XPath xPathEvaluator = XPathFactory.newInstance (). newXPath ();

This is safe because each thread gets its own factory (thanks to newInstance() ). No need to sync here.

What you can not safely do is get the factory only once, and then share it between threads without synchronization, for example, like singleton. The same applies to an XPath instance ( xPathEvaluator ).

+11
source

"One of them is that XPathFactory.newInstance () is very expensive:"

True statement! I noticed that for each thread calling newInstance (), jaxp.properties should be located in the classpath and read:

 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 creates its own call (for zlib, I believe), and unpacks the jar, which requires disk I / O and conversion to a zip converter. In this case, we had 1400+ threads waiting for this lock.

+3
source

All Articles