Bind CodecDataObject string instances 77/81877/2
authorRobert Varga <robert.varga@pantheon.tech>
Thu, 2 May 2019 14:13:33 +0000 (16:13 +0200)
committerRobert Varga <robert.varga@pantheon.tech>
Thu, 2 May 2019 16:20:25 +0000 (18:20 +0200)
Heap analysis of the classes we generated on top of CodecDataObject
indicates we have an unnecessarily-large class constant pool. This
boils down our usage of string constants we pass back to
CodecDataObject -- which are coming from QName, but are not guaranteed
to be interned.

Aside from increasing heap consumption, this has a downside of not
requiring deep string comparisons during lookup -- which we want to
avoid if at all possible.

This patch updates generation strategy to create explicit constant
fields, which are bound to direct references to Strings used in
QNames -- resulting in the same objects being used.

JIRA: MDSAL-442
Change-Id: I10ef4ae49525d3f45076260e9438863b5830cf9a
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/ClassGeneratorBridge.java [new file with mode: 0644]
binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/CodecDataObjectBridge.java [deleted file]
binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/CodecDataObjectGenerator.java

diff --git a/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/ClassGeneratorBridge.java b/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/ClassGeneratorBridge.java
new file mode 100644 (file)
index 0000000..cc6dcca
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.mdsal.binding.dom.codec.impl;
+
+import static com.google.common.base.Verify.verifyNotNull;
+
+import com.google.common.annotations.Beta;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * Bridge for initializing generated instance constants during class loading time. This class is public only due to
+ * implementation restrictions and can change at any time.
+ */
+@Beta
+public final class ClassGeneratorBridge {
+    interface BridgeProvider {
+
+    }
+
+    interface LocalNameProvider extends BridgeProvider {
+
+        @NonNull String resolveLocalName(@NonNull String methodName);
+    }
+
+    interface NodeContextSupplierProvider extends BridgeProvider {
+
+        @NonNull NodeContextSupplier resolveNodeContextSupplier(@NonNull String methodName);
+    }
+
+    private static final ThreadLocal<BridgeProvider> CURRENT_CUSTOMIZER = new ThreadLocal<>();
+
+    private ClassGeneratorBridge() {
+
+    }
+
+    public static @NonNull NodeContextSupplier resolveNodeContextSupplier(final @NonNull String methodName) {
+        return current(NodeContextSupplierProvider.class).resolveNodeContextSupplier(methodName);
+    }
+
+    public static @NonNull String resolveLocalName(final @NonNull String methodName) {
+        return current(LocalNameProvider.class).resolveLocalName(methodName);
+    }
+
+    static @Nullable BridgeProvider setup(final @NonNull BridgeProvider next) {
+        final BridgeProvider prev = CURRENT_CUSTOMIZER.get();
+        CURRENT_CUSTOMIZER.set(verifyNotNull(next));
+        return prev;
+    }
+
+    static void tearDown(final @Nullable BridgeProvider prev) {
+        if (prev == null) {
+            CURRENT_CUSTOMIZER.remove();
+        } else {
+            CURRENT_CUSTOMIZER.set(prev);
+        }
+    }
+
+    private static <T extends BridgeProvider> @NonNull T current(final Class<T> requested) {
+        return requested.cast(verifyNotNull(CURRENT_CUSTOMIZER.get(), "No customizer attached"));
+    }
+}
diff --git a/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/CodecDataObjectBridge.java b/binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/CodecDataObjectBridge.java
deleted file mode 100644 (file)
index d79340c..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.mdsal.binding.dom.codec.impl;
-
-import static com.google.common.base.Verify.verifyNotNull;
-
-import com.google.common.annotations.Beta;
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.mdsal.binding.dom.codec.impl.CodecDataObjectGenerator.Fixed;
-
-/**
- * Bridge for initializing {@link CodecDataObject} instance constants during class loading time. This class is public
- * only due to implementation restrictions and can change at any time.
- */
-@Beta
-public final class CodecDataObjectBridge {
-    private static final ThreadLocal<Fixed<?>> CURRENT_CUSTOMIZER = new ThreadLocal<>();
-
-    private CodecDataObjectBridge() {
-
-    }
-
-    public static @NonNull NodeContextSupplier resolve(final @NonNull String methodName) {
-        return current().resolve(methodName);
-    }
-
-    static @Nullable Fixed<?> setup(final @NonNull Fixed<?> next) {
-        final Fixed<?> prev = CURRENT_CUSTOMIZER.get();
-        CURRENT_CUSTOMIZER.set(verifyNotNull(next));
-        return prev;
-    }
-
-    static void tearDown(final @Nullable Fixed<?> prev) {
-        if (prev == null) {
-            CURRENT_CUSTOMIZER.remove();
-        } else {
-            CURRENT_CUSTOMIZER.set(prev);
-        }
-    }
-
-    private static @NonNull Fixed<?> current() {
-        return verifyNotNull(CURRENT_CUSTOMIZER.get(), "No customizer attached");
-    }
-}
index 4bee13e5efbf7a8224c3305932fd974ce95784a7..c97ca3c254731b3c147f1802f9d9a14ffba3c47f 100644 (file)
@@ -54,6 +54,9 @@ import net.bytebuddy.jar.asm.MethodVisitor;
 import net.bytebuddy.jar.asm.Opcodes;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.BridgeProvider;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
@@ -136,26 +139,28 @@ import org.slf4j.LoggerFactory;
  * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
  * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
  * <ul>
- * <li>During code generation, the context fields are pointed towards {@link CodecDataObjectBridge#resolve(String)} and
- *     {@link CodecDataObjectBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
+ * <li>During code generation, the context fields are pointed towards
+ *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
+ *     {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
  *     in the context of a class initializer.</li>
  * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
  *     class loading operation. At this point the generator installs itself as the current generator for this thread via
- *     {@link CodecDataObjectBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
+ *     {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
  * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
- *     point the static invocations will be redirect to {@link #resolve(String)} and {@link #resolveKey(String)}
- *     methods, thus initializing the fields to the intended constants.</li>
+ *     point the static invocations will be redirect to {@link #resolveNodeContextSupplier(String)} and
+ *     {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
  * <li>Before returning from the class loading call, the generator will detach itself via
- *     {@link CodecDataObjectBridge#tearDown(CodecDataObjectGenerator)}.</li>
+ *     {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
  * </ul>
  *
  * <p>
  * This strategy works due to close cooperation with the target ClassLoader, as the entire code generation and loading
  * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
  */
-abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
+abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T>, BridgeProvider {
     // Not reusable defintion: we can inline NodeContextSuppliers without a problem
-    static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
+    static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
+            implements NodeContextSupplierProvider {
         private final ImmutableMap<Method, NodeContextSupplier> properties;
 
         private Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
@@ -183,32 +188,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
 
         @Override
-        public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
-            final Fixed<?> prev = CodecDataObjectBridge.setup(this);
-            try {
-                final Class<T> result = loader.get();
-
-                /*
-                 * This a bit of magic to support NodeContextSupplier constants. These constants need to be resolved
-                 * while we have the information needed to find them -- that information is being held in this instance
-                 * and we leak it to a thread-local variable held by CodecDataObjectBridge.
-                 *
-                 * By default the JVM will defer class initialization to first use, which unfortunately is too late for
-                 * us, and hence we need to force class to initialize.
-                 */
-                try {
-                    Class.forName(result.getName(), true, result.getClassLoader());
-                } catch (ClassNotFoundException e) {
-                    throw new LinkageError("Failed to find newly-defined " + result, e);
-                }
-
-                return result;
-            } finally {
-                CodecDataObjectBridge.tearDown(prev);
-            }
-        }
-
-        @NonNull NodeContextSupplier resolve(final @NonNull String methodName) {
+        public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
             final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
@@ -217,7 +197,8 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     }
 
     // Reusable definition: we have to rely on context lookups
-    private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
+    static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
+            implements LocalNameProvider {
         private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
         private final Map<Method, Class<?>> daoProperties;
 
@@ -232,14 +213,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         @Override
         Builder<T> generateGetters(final Builder<T> builder) {
             Builder<T> tmp = builder;
-            for (Entry<Method, ValueNodeCodecContext> entry : simpleProperties.entrySet()) {
-                final Method method = entry.getKey();
+            for (Method method : simpleProperties.keySet()) {
                 LOG.trace("Generating for simple method {}", method);
                 final String methodName = method.getName();
                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
-                    new SimpleGetterMethodImplementation(methodName, retType,
-                        entry.getValue().getSchema().getQName().getLocalName()));
+                    new SimpleGetterMethodImplementation(methodName, retType));
             }
             for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
                 final Method method = entry.getKey();
@@ -260,6 +239,14 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             ret.addAll(daoProperties.keySet());
             return ret;
         }
+
+        @Override
+        public String resolveLocalName(final String methodName) {
+            final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
+                    .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
+            verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
+            return found.get().getValue().getSchema().getQName().getLocalName();
+        }
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
@@ -355,6 +342,32 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
                 .make());
     }
 
+    @Override
+    public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
+        final BridgeProvider prev = ClassGeneratorBridge.setup(this);
+        try {
+            final Class<T> result = loader.get();
+
+            /*
+             * This a bit of magic to support NodeContextSupplier constants. These constants need to be resolved
+             * while we have the information needed to find them -- that information is being held in this instance
+             * and we leak it to a thread-local variable held by CodecDataObjectBridge.
+             *
+             * By default the JVM will defer class initialization to first use, which unfortunately is too late for
+             * us, and hence we need to force class to initialize.
+             */
+            try {
+                Class.forName(result.getName(), true, result.getClassLoader());
+            } catch (ClassNotFoundException e) {
+                throw new LinkageError("Failed to find newly-defined " + result, e);
+            }
+
+            return result;
+        } finally {
+            ClassGeneratorBridge.tearDown(prev);
+        }
+    }
+
     abstract Builder<T> generateGetters(Builder<T> builder);
 
     abstract ArrayList<Method> getterMethods();
@@ -468,26 +481,49 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
+    /*
+     * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
+     * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
+     * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
+     * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
+     * on the constant pool entry to resolve to the same object.
+     */
     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", AtomicReferenceFieldUpdater.class, String.class);
+        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
+            "resolveLocalName", String.class);
+        private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
 
-        private final String localName;
+        // getFoo$$$S
+        private final String stringName;
 
-        SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType,
-                final String localName) {
+        SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
             super(methodName, retType);
-            this.localName = requireNonNull(localName);
+            this.stringName = methodName + "$$$S";
+        }
+
+        @Override
+        public InstrumentedType prepare(final InstrumentedType instrumentedType) {
+            final InstrumentedType tmp = super.prepare(instrumentedType)
+                    // private static final String getFoo$$$S;
+                    .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
+
+            return tmp.withInitializer(new ByteCodeAppender.Simple(
+                // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
+                new TextConstant(methodName),
+                BRIDGE_RESOLVE,
+                putField(tmp, stringName)));
         }
 
         @Override
         public ByteCodeAppender appender(final Target implementationTarget) {
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
-                // return (FooType) codecMember(getFoo$$$A, "foo");
+                // return (FooType) codecMember(getFoo$$$A, getFoo$$$S);
                 THIS,
                 getField(instrumentedType, arfuName),
-                new TextConstant(localName),
+                getField(instrumentedType, stringName),
                 CODEC_MEMBER,
                 TypeCasting.to(retType),
                 MethodReturn.REFERENCE);
@@ -523,8 +559,8 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", AtomicReferenceFieldUpdater.class, NodeContextSupplier.class);
-        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(CodecDataObjectBridge.class,
-            "resolve", String.class);
+        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
+            "resolveNodeContextSupplier", String.class);
         private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
 
         // getFoo$$$C