BUG 2954 : Thread local DocumentBuilder's for XmlUtil
[controller.git] / opendaylight / netconf / netconf-util / src / main / java / org / opendaylight / controller / netconf / util / xml / XmlUtil.java
index 6408fce5d39b199c1105807619bf9e4e0198c4f6..65754e6b34cd55f5e11f7fc481115fbc0da39de4 100644 (file)
@@ -68,6 +68,22 @@ public final class XmlUtil {
         BUILDER_FACTORY = factory;
     }
 
+    private static final ThreadLocal<DocumentBuilder> DEFAULT_DOM_BUILDER = new ThreadLocal<DocumentBuilder>(){
+        @Override
+        protected DocumentBuilder initialValue() {
+            try {
+                return BUILDER_FACTORY.newDocumentBuilder();
+            } catch (ParserConfigurationException e) {
+                throw new IllegalStateException("Failed to create threadLocal dom builder", e);
+            }
+        }
+
+        @Override
+        public void set(DocumentBuilder value) {
+            throw new UnsupportedOperationException();
+        }
+    };
+
     private XmlUtil() {
         throw new UnsupportedOperationException("Utility class");
     }
@@ -90,13 +106,7 @@ public final class XmlUtil {
     // along with XmlElement
 
     public static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
-        DocumentBuilder dBuilder;
-        try {
-            dBuilder = BUILDER_FACTORY.newDocumentBuilder();
-        } catch (ParserConfigurationException e) {
-            throw new IllegalStateException("Failed to parse XML document", e);
-        }
-        Document doc = dBuilder.parse(xmlContent);
+        Document doc = DEFAULT_DOM_BUILDER.get().parse(xmlContent);
 
         doc.getDocumentElement().normalize();
         return doc;
@@ -107,12 +117,7 @@ public final class XmlUtil {
     }
 
     public static Document newDocument() {
-        try {
-            DocumentBuilder builder = BUILDER_FACTORY.newDocumentBuilder();
-            return builder.newDocument();
-        } catch (ParserConfigurationException e) {
-            throw new IllegalStateException("Failed to create document", e);
-        }
+        return DEFAULT_DOM_BUILDER.get().newDocument();
     }
 
     public static Element createElement(final Document document, final String qName, final Optional<String> namespaceURI) {