Eliminate thread-blocking on NetconfMessage.toString() 28/109928/5
authorMatej Sramcik <matej.sramcik@pantheon.tech>
Tue, 23 Jan 2024 13:06:29 +0000 (14:06 +0100)
committerRobert Varga <nite@hq.sk>
Thu, 1 Feb 2024 00:28:00 +0000 (00:28 +0000)
The NetconfMessage.toString() method is synchronized on the
TRANSFORMER.
This creates bottleneck if method is processing a lot of messages.

Used XmlUtil.toString() instead of Transformer to fix the issue.

JIRA: NETCONF-1227
Change-Id: I26ec52bc53787801d2a01db4a8096a855a30718a
Signed-off-by: Matej Sramcik <matej.sramcik@pantheon.tech>
protocol/netconf-api/src/main/java/org/opendaylight/netconf/api/messages/NetconfMessage.java

index 1d27ff7125af951ae73f41c30303c5a69a304349..8dd9a6871f752bc74d9926c1563418d1feaaa7fb 100644 (file)
@@ -9,14 +9,7 @@ package org.opendaylight.netconf.api.messages;
 
 import static java.util.Objects.requireNonNull;
 
-import java.io.StringWriter;
 import java.util.Map;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
 import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.netconf.api.DocumentedException;
 import org.opendaylight.netconf.api.NamespaceURN;
@@ -30,20 +23,6 @@ import org.w3c.dom.Document;
  * NetconfMessage represents a wrapper around {@link Document}.
  */
 public class NetconfMessage {
-    private static final Transformer TRANSFORMER;
-
-    static {
-        final Transformer t;
-        try {
-            t = XmlUtil.newIndentingTransformer();
-        } catch (TransformerConfigurationException e) {
-            throw new ExceptionInInitializerError(e);
-        }
-        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-
-        TRANSFORMER = t;
-    }
-
     private final @NonNull Document document;
 
     public NetconfMessage(final Document document) {
@@ -104,18 +83,6 @@ public class NetconfMessage {
 
     @Override
     public final String toString() {
-        final var result = new StreamResult(new StringWriter());
-        final var source = new DOMSource(document.getDocumentElement());
-
-        try {
-            // Slight critical section is a tradeoff. This should be reasonably fast.
-            synchronized (TRANSFORMER) {
-                TRANSFORMER.transform(source, result);
-            }
-        } catch (TransformerException e) {
-            throw new IllegalStateException("Failed to encode document", e);
-        }
-
-        return result.getWriter().toString();
+        return XmlUtil.toString(document);
     }
 }