/** * <p> * Wraps another matcher but caches the result of previously matched elements. Caching can be important if a * matcher requires expensive calculations. * </p> * <p> * <b>Warning</b>: The cache will hold {@code evictionSize} elements and evict a random element once the cache * contains more than the specified amount of elements. Cached elements are referenced strongly and might cause * a memory leak if instance are of a significant size. Using {@link ElementMatchers#cached(ElementMatcher, ConcurrentMap)} * allows for explicit control over cache eviction. * </p> * * @param matcher The actual matcher for which the results are cached. * @param evictionSize The maximum amount of elements that are stored in the cache. Must be a positive number. * @param <T> The type of the matched object. * @return A matcher that stores the results of a previous matching in the supplied map. */ public static <T> ElementMatcher.Junction<T> cached(ElementMatcher<? super T> matcher, int evictionSize) { if (evictionSize < 1) { throw new IllegalArgumentException("Eviction size must be a positive number: " + evictionSize); } return new CachingMatcher.WithInlineEviction<T>(matcher, new ConcurrentHashMap<T, Boolean>(), evictionSize); }