BUG 2954 : Thread local DocumentBuilder's for XmlUtil 60/17860/8
authorTomas Cere <tcere@cisco.com>
Tue, 7 Apr 2015 13:49:33 +0000 (15:49 +0200)
committerTony Tkacik <ttkacik@cisco.com>
Fri, 24 Apr 2015 15:42:44 +0000 (15:42 +0000)
Increases performance by reusing cached DocumentBuilder instances.

Change-Id: I5aab6b4caa960878b647e6868377d62dd6262cd9
Signed-off-by: Tomas Cere <tcere@cisco.com>
opendaylight/netconf/netconf-util/src/main/java/org/opendaylight/controller/netconf/util/xml/XmlUtil.java

index 6408fce..65754e6 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) {

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.