Use ImmutableMaps for lazy augmentations initialization 44/78044/4
authorRobert Varga <robert.varga@pantheon.tech>
Wed, 14 Nov 2018 15:40:29 +0000 (16:40 +0100)
committerRobert Varga <robert.varga@pantheon.tech>
Thu, 22 Nov 2018 13:50:34 +0000 (14:50 +0100)
Rather than tracking lookups in two separate ConcurrentMaps, we
perform locked atomic updates in copy-on-write immutable structure.

The two lookup maps are kept in ImmutableMaps, which offer tighter
packing and do not incur any further volatile reads beyond getting
a reference to them.

This results in lower memory overhead, as the maps are more tightly
packed and also biases performance towards the dominant use case,
which is pure lookups.

JIRA: MDSAL-391
Change-Id: I65ecb25a5d364040be44df144000d1bbbc2a922e
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
(cherry picked from commit d349008b4936f7e128ec292a66e05f3e9bd57e73)

binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/mdsal/binding/dom/codec/impl/DataObjectCodecContext.java

index 85cf08cc78861d348b6515b943ea75c3dfb19905..e1004241e0ae901512fa535aad891bc5f4c1b1f0 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.mdsal.binding.dom.codec.impl;
 
 import static com.google.common.base.Verify.verifyNotNull;
+import static java.util.Objects.requireNonNull;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
@@ -23,17 +24,19 @@ import java.lang.reflect.Proxy;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.HashMap;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
 import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
 import org.opendaylight.mdsal.binding.model.api.Type;
 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
+import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
@@ -60,10 +63,22 @@ import org.slf4j.LoggerFactory;
 
 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
         extends DataContainerCodecContext<D, T> {
+    private static final class Augmentations implements Immutable {
+        final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYang;
+        final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStream;
+
+        Augmentations(final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYang,
+            final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStream) {
+            this.byYang = requireNonNull(byYang);
+            this.byStream = requireNonNull(byStream);
+        }
+    }
+
     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
     private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
+    private static final Augmentations EMPTY_AUGMENTATIONS = new Augmentations(ImmutableMap.of(), ImmutableMap.of());
     private static final Method[] EMPTY_METHODS = new Method[0];
 
     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
@@ -75,9 +90,11 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
     private final MethodHandle proxyConstructor;
     private final Method[] propertyMethods;
 
-    private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
-            new ConcurrentHashMap<>();
-    private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
+    @SuppressWarnings("rawtypes")
+    private static final AtomicReferenceFieldUpdater<DataObjectCodecContext, Augmentations>
+        AUGMENTATIONS_UPDATER = AtomicReferenceFieldUpdater.newUpdater(DataObjectCodecContext.class,
+            Augmentations.class, "augmentations");
+    private volatile Augmentations augmentations = EMPTY_AUGMENTATIONS;
 
     private volatile ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> mismatchedAugmented = ImmutableMap.of();
 
@@ -150,12 +167,80 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
         }
     }
 
+    // This method could be synchronized, but that would mean that concurrent attempts to load an invalid augmentation
+    // would end up being unnecessarily contended -- blocking real progress and not being able to run concurrently
+    // while producing no effect. We therefore use optimistic read + CAS.
     private void reloadAllAugmentations() {
-        for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
-            final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
+        // Load current values
+        Augmentations oldAugmentations = augmentations;
+
+        // FIXME: can we detect when we have both maps fully populated and skip all of this?
+
+        // Scratch space for additions
+        final Map<PathArgument, DataContainerCodecPrototype<?>> addByYang = new HashMap<>();
+        final Map<Class<?>, DataContainerCodecPrototype<?>> addByStream = new HashMap<>();
+
+        // Iterate over all possibilities, checking for modifications.
+        for (final Type augment : possibleAugmentations.values()) {
+            final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment);
             if (augProto != null) {
-                byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
-                byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
+                final PathArgument yangArg = augProto.getYangArg();
+                final Class<?> bindingClass = augProto.getBindingClass();
+                if (!oldAugmentations.byYang.containsKey(yangArg)) {
+                    if (addByYang.putIfAbsent(yangArg, augProto) == null) {
+                        LOG.trace("Discovered new YANG mapping {} -> {} in {}", yangArg, augProto, this);
+                    }
+                }
+                if (!oldAugmentations.byStream.containsKey(bindingClass)) {
+                    if (addByStream.putIfAbsent(bindingClass, augProto) == null) {
+                        LOG.trace("Discovered new class mapping {} -> {} in {}", bindingClass, augProto, this);
+                    }
+                }
+            }
+        }
+
+        while (true) {
+            if (addByYang.isEmpty() && addByStream.isEmpty()) {
+                LOG.trace("No new augmentations discovered in {}", this);
+                return;
+            }
+
+            // We have some additions, propagate them out
+            final Augmentations newAugmentations = new Augmentations(concatMaps(oldAugmentations.byYang, addByYang),
+                concatMaps(oldAugmentations.byStream, addByStream));
+            if (AUGMENTATIONS_UPDATER.compareAndSet(this, oldAugmentations, newAugmentations)) {
+                // Success, we are done
+                return;
+            }
+
+            // We have raced installing new augmentations, read them again, remove everything present in the installed
+            // once and try again. This may mean that we end up not doing anything, but that's fine.
+            oldAugmentations = augmentations;
+
+            // We could use Map.removeAll(oldAugmentations.byYang.keySet()), but that forces the augmentation's keyset
+            // to be materialized, which we otherwise do not need. Hence we do this the other way around, instantiating
+            // our temporary maps' keySets and iterating over them. That's fine as we'll be throwing those maps away.
+            removeMapKeys(addByYang, oldAugmentations.byYang);
+            removeMapKeys(addByStream, oldAugmentations.byStream);
+        }
+    }
+
+    private static <K, V> ImmutableMap<K, V> concatMaps(final ImmutableMap<K, V> old, final Map<K, V> add) {
+        if (add.isEmpty()) {
+            return old;
+        }
+
+        final Builder<K, V> builder = ImmutableMap.builderWithExpectedSize(old.size() + add.size());
+        builder.putAll(old);
+        builder.putAll(add);
+        return builder.build();
+    }
+
+    private static <K, V> void removeMapKeys(final Map<K, V> removeFrom, final ImmutableMap<K, V> map) {
+        final Iterator<K> it = removeFrom.keySet().iterator();
+        while (it.hasNext()) {
+            if (map.containsKey(it.next())) {
+                it.remove();
             }
         }
     }
@@ -289,13 +374,15 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
     }
 
     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
-        final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
+        final DataContainerCodecPrototype<?> firstTry = augmentations.byYang.get(arg);
         if (firstTry != null) {
             return firstTry;
         }
         if (possibleAugmentations.containsKey(arg)) {
+            // Try to load augmentations, which will potentially update knownAugmentations, hence we re-load that field
+            // again.
             reloadAllAugmentations();
-            return byYangAugmented.get(arg);
+            return augmentations.byYang.get(arg);
         }
         return null;
     }
@@ -336,9 +423,11 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
         return false;
     }
 
-    @Nullable
-    private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
-        final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
+    private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
+            final @NonNull Class<?> childClass) {
+        // Perform a single load, so we can reuse it if we end up going to the reflection-based slow path
+        final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> local = augmentations.byStream;
+        final DataContainerCodecPrototype<?> childProto = local.get(childClass);
         if (childProto != null) {
             return childProto;
         }
@@ -356,13 +445,14 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
         @SuppressWarnings("rawtypes")
         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
         if (getBindingClass().equals(augTarget)) {
-            for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
+            for (final DataContainerCodecPrototype<?> realChild : local.values()) {
                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
                     return cacheMismatched(childClass, realChild);
                 }
             }
         }
+        LOG.trace("Failed to resolve {} as a valid augmentation in {}", childClass, this);
         return null;
     }
 
@@ -381,6 +471,7 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
         builder.put(childClass, prototype);
 
         mismatchedAugmented = builder.build();
+        LOG.trace("Cached mismatched augmentation {} -> {} in {}", childClass, prototype, this);
         return prototype;
     }
 
@@ -440,7 +531,7 @@ abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeCo
                 }
             }
         }
-        for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
+        for (final DataContainerCodecPrototype<?> value : augmentations.byStream.values()) {
             final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
             if (augData.isPresent()) {
                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));