Split STATIC_CODECS into per-type caches
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / BitsCodec.java
index 267c4df6e5e3cd12fbc43323d83fb7d3eb7ad2b8..f5b0908961deabb7e0a6d253e47ad8043053e928 100644 (file)
@@ -7,7 +7,11 @@
  */
 package org.opendaylight.mdsal.binding.dom.codec.impl;
 
-import com.google.common.base.Preconditions;
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.cache.Cache;
+import com.google.common.cache.CacheBuilder;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import java.lang.invoke.MethodHandle;
@@ -23,36 +27,51 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 import java.util.TreeSet;
-import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import org.eclipse.jdt.annotation.NonNull;
 import org.opendaylight.mdsal.binding.dom.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
 
 final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
+    /*
+     * Use identity comparison for keys and allow classes to be GCd themselves.
+     *
+     * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
+     * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
+     * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
+     *
+     *     "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
+     *      recently-used soft references."
+     */
+    private static final Cache<Class<?>, @NonNull BitsCodec> CACHE = CacheBuilder.newBuilder().weakKeys().softValues()
+        .build();
     private static final MethodType CONSTRUCTOR_INVOKE_TYPE = MethodType.methodType(Object.class, Boolean[].class);
 
     // Ordered by position
-    private final Map<String, Method> getters;
+    private final ImmutableMap<String, Method> getters;
     // Ordered by lexical name
-    private final Set<String> ctorArgs;
+    private final ImmutableSet<String> ctorArgs;
     private final MethodHandle ctor;
 
     private BitsCodec(final Class<?> typeClass, final MethodHandle ctor, final Set<String> ctorArgs,
             final Map<String, Method> getters) {
         super(typeClass);
-        this.ctor = Preconditions.checkNotNull(ctor);
+        this.ctor = requireNonNull(ctor);
         this.ctorArgs = ImmutableSet.copyOf(ctorArgs);
         this.getters = ImmutableMap.copyOf(getters);
     }
 
-    static Callable<BitsCodec> loader(final Class<?> returnType, final BitsTypeDefinition rootType) {
-        return () -> {
+    static @NonNull BitsCodec of(final Class<?> returnType, final BitsTypeDefinition rootType)
+            throws ExecutionException {
+        return CACHE.get(returnType, () -> {
             final Map<String, Method> getters = new LinkedHashMap<>();
             final Set<String> ctorArgs = new TreeSet<>();
 
             for (Bit bit : rootType.getBits()) {
-                final Method valueGetter = returnType.getMethod("is" + BindingMapping.getClassName(bit.getName()));
+                final Method valueGetter = returnType.getMethod(BindingMapping.GETTER_PREFIX
+                    + BindingMapping.getClassName(bit.getName()));
                 ctorArgs.add(bit.getName());
                 getters.put(bit.getName(), valueGetter);
             }
@@ -66,23 +85,23 @@ final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec
             final MethodHandle ctor = MethodHandles.publicLookup().unreflectConstructor(constructor)
                     .asSpreader(Boolean[].class, ctorArgs.size()).asType(CONSTRUCTOR_INVOKE_TYPE);
             return new BitsCodec(returnType, ctor, ctorArgs, getters);
-        };
+        });
     }
 
     @Override
+    @SuppressWarnings("checkstyle:illegalCatch")
     public Object deserialize(final Object input) {
-        Preconditions.checkArgument(input instanceof Set);
+        checkArgument(input instanceof Set);
         @SuppressWarnings("unchecked")
         final Set<String> casted = (Set<String>) input;
 
         /*
-         * We can do this walk based on field set sorted by name,
-         * since constructor arguments in Java Binding are sorted by name.
+         * We can do this walk based on field set sorted by name, since constructor arguments in Java Binding are
+         * sorted by name.
          *
-         * This means we will construct correct array for construction
-         * of bits object.
+         * This means we will construct correct array for construction of bits object.
          */
-        final Boolean args[] = new Boolean[ctorArgs.size()];
+        final Boolean[] args = new Boolean[ctorArgs.size()];
         int currentArg = 0;
         for (String value : ctorArgs) {
             args[currentArg++] = casted.contains(value);
@@ -101,7 +120,7 @@ final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec
         for (Entry<String, Method> valueGet : getters.entrySet()) {
             final Boolean value;
             try {
-                 value = (Boolean) valueGet.getValue().invoke(input);
+                value = (Boolean) valueGet.getValue().invoke(input);
             } catch (IllegalAccessException | InvocationTargetException e) {
                 throw new IllegalArgumentException("Failed to get bit " + valueGet.getKey(), e);
             }