aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/collections/MethodCache.java
blob: 9f5beb3a9830d2bd2a0e2a646e1263255f7704df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// 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 (method == null) {
            method = lookupMethod(object);
            if (method != null) {
                pair = new Pair<>(object.getClass(), method);
                if (onPut != null)
                    onPut.accept(object.getClass().getName());
                cache.put(object.getClass().getName(), new WeakReference<>(pair));
            }
        }
        return method;
    }

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

}