|
4 | 4 | */ |
5 | 5 | package org.mockito.internal.invocation; |
6 | 6 |
|
7 | | -import java.lang.reflect.Method; |
8 | | - |
9 | 7 | import org.mockito.ArgumentMatcher; |
10 | 8 |
|
| 9 | +import java.lang.reflect.Method; |
| 10 | +import java.util.concurrent.ConcurrentHashMap; |
| 11 | +import java.util.concurrent.ConcurrentMap; |
| 12 | + |
11 | 13 | @SuppressWarnings({"unchecked", "rawtypes"}) |
12 | 14 | public class TypeSafeMatching implements ArgumentMatcherAction { |
13 | 15 |
|
14 | 16 | private static final ArgumentMatcherAction TYPE_SAFE_MATCHING_ACTION = new TypeSafeMatching(); |
15 | 17 |
|
| 18 | + /** |
| 19 | + * This cache is in theory unbounded. However, its max size is bounded by the number of types of argument matchers |
| 20 | + * that are both in the system and being used, which is expected to bound the cache's size to a low number |
| 21 | + * (<200) in all but the most contrived cases, and form a small percentage of the overall memory usage of those |
| 22 | + * classes. |
| 23 | + */ |
| 24 | + private static final ConcurrentMap<Class<?>, Class<?>> argumentTypeCache = |
| 25 | + new ConcurrentHashMap<>(); |
| 26 | + |
16 | 27 | private TypeSafeMatching() {} |
17 | 28 |
|
18 | 29 | public static ArgumentMatcherAction matchesTypeSafe() { |
@@ -39,11 +50,23 @@ private static boolean isCompatible(ArgumentMatcher<?> argumentMatcher, Object a |
39 | 50 | return expectedArgumentType.isInstance(argument); |
40 | 51 | } |
41 | 52 |
|
| 53 | + private static Class<?> getArgumentType(ArgumentMatcher<?> matcher) { |
| 54 | + Class<?> argumentMatcherType = matcher.getClass(); |
| 55 | + Class<?> cached = argumentTypeCache.get(argumentMatcherType); |
| 56 | + // Avoids a lambda allocation on invocations >=2 for worse perf on invocation 1. |
| 57 | + if (cached != null) { |
| 58 | + return cached; |
| 59 | + } else { |
| 60 | + return argumentTypeCache.computeIfAbsent( |
| 61 | + argumentMatcherType, unusedKey -> getArgumentTypeUncached(matcher)); |
| 62 | + } |
| 63 | + } |
| 64 | + |
42 | 65 | /** |
43 | 66 | * Returns the type of {@link ArgumentMatcher#matches(Object)} of the given |
44 | 67 | * {@link ArgumentMatcher} implementation. |
45 | 68 | */ |
46 | | - private static Class<?> getArgumentType(ArgumentMatcher<?> argumentMatcher) { |
| 69 | + private static Class<?> getArgumentTypeUncached(ArgumentMatcher<?> argumentMatcher) { |
47 | 70 | Method[] methods = argumentMatcher.getClass().getMethods(); |
48 | 71 |
|
49 | 72 | for (Method method : methods) { |
|