// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;

import com.yahoo.concurrent.CopyOnWriteHashMap;

import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.function.Consumer;

/**
 * This will cache methods solved by reflection as reflection is expensive.
 * Note that if the bundle from which the method is removed/changed you might have
 * a problem... A ClassCastException might be one indication. Then clearing the cache and retrying it
 * once to see if it goes away might be a solution.
 * @author baldersheim
 */
public final class MethodCache {

    private final String methodName;
    private final CopyOnWriteHashMap<String, WeakReference<Pair<Class<?>, Method>>> cache = new CopyOnWriteHashMap<>();

    public MethodCache(String methodName) {
        this.methodName = methodName;
    }

    /*
     Clear all cached methods. Might be a wise thing to do, if you have cached some methods
     that have changed due to new bundles being reloaded.
    */
    public void clear() {
        cache.clear();
    }

    public Method get(Object object) {
        return get(object, null);
    }

    public Method get(Object object, Consumer<String> onPut) {
        WeakReference<Pair<Class<?>, Method>> value = cache.get(object.getClass().getName());
        Pair<Class<?>, Method> pair = value == null ? null : value.get();
        if (pair != null && pair.getFirst() != object.getClass()) {
            cache.clear();
            pair = null;
        }
        Method method = pair == null ? null : pair.getSecond();
        if (pair == null) {
            method = lookupMethod(object);
            pair = new Pair<>(object.getClass(), method);
            cache.put(object.getClass().getName(), new WeakReference<>(pair));
            if (onPut != null)
                onPut.accept(object.getClass().getName());
        }
        return method;
    }

    private Method lookupMethod(Object object)  {
        try {
            return object.getClass().getMethod(methodName);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }

}

@@ -183,44 +183,8 @@
 p;%0A%0A
-import java.lang.ref.WeakReference;%0A
 impo
@@ -212,16 +212,16 @@
 Method;%0A
+
 import j
@@ -709,30 +709,16 @@
 String, 
-WeakReference%3C
 Pair%3CCla
@@ -732,17 +732,16 @@
 Method%3E%3E
-%3E
  cache =
@@ -1230,30 +1230,16 @@
         
-WeakReference%3C
 Pair%3CCla
@@ -1256,15 +1256,13 @@
 hod%3E
-%3E value
+ pair
  = c
@@ -1304,82 +1304,8 @@
 ));%0A
-        Pair%3CClass%3C?%3E, Method%3E pair = value == null ? null : value.get();%0A
     
@@ -1569,66 +1569,8 @@
 t);%0A
-            pair = new Pair%3C%3E(object.getClass(), method);%0A
     
@@ -1624,28 +1624,40 @@
 new 
-WeakReference%3C%3E(pair
+Pair%3C%3E(object.getClass(), method
 ));%0A

Remove weak-refs