<p>Is the standard Java 1.6 <a href="http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">javax.xml.parsers.DocumentBuilder</a> class thread safe? Is it safe to call the parse() method from several threads in parallel?</p>

<p>The JavaDoc doesn't mention the issue, but the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html" rel="noreferrer">JavaDoc for the same class</a> in Java 1.4 specifically says that it <em>isn't</em> meant to be concurrent; so can I assume that in 1.6 it is?</p>

<p>The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.</p>

[{'answer_id': 56815, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 6, 'selected': True, 'text': '<p>Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:</p>\n\n<pre><code>private static final ThreadLocal&lt;DocumentBuilder&gt; builderLocal =\n    new ThreadLocal&lt;DocumentBuilder&gt;() {\n        @Override protected DocumentBuilder initialValue() {\n            try {\n                return\n                    DocumentBuilderFactory\n                        .newInstance(\n                            "xx.MyDocumentBuilderFactory",\n                            getClass().getClassLoader()\n                        ).newDocumentBuilder();\n            } catch (ParserConfigurationException exc) {\n                throw new IllegalArgumentException(exc);\n            }\n        }\n    };\n</code></pre>\n\n<p>(Disclaimer: Not so much as attempted to compile the code.)</p>\n'}, {'answer_id': 231433, 'author': 'Trenton', 'author_id': 2601671, 'author_profile': 'https://Stackoverflow.com/users/2601671', 'pm_score': 5, 'selected': False, 'text': "<p>There's a reset() method on DocumentBuilder which restores it to the state when it was first created. If you're going the ThreadLocal route, don't forget to call this or you're hosed.</p>\n"}, {'answer_id': 18823295, 'author': 'Koray Güclü', 'author_id': 1242601, 'author_profile': 'https://Stackoverflow.com/users/1242601', 'pm_score': 2, 'selected': False, 'text': '<p>You can also check this code to make further optimization <a href="https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java" rel="nofollow">https://svn.apache.org/repos/asf/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/xml/XmlUtil.java</a></p>\n'}]
['https://Stackoverflow.com/questions/56737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1605/']