ConcurrentMapBasedToLongFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Long> implements ToLongFunction<INPUT> { @Override public long applyAsLong(final INPUT input) { final KEY key = keyFunction.apply(input); return computeIfAbsent(key, givenKey -> Long.valueOf(function.applyAsLong(input))) .longValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedToLongFunctionMemoizer(
            final ConcurrentMap<KEY, Long> cache,
            final Function<INPUT, KEY> keyFunction,
            final ToLongFunction<INPUT> function); @Override long applyAsLong(final INPUT input);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final ToLongFunction<String> function = input -> 123L; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToLongFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong("123"); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final ToLongFunction<String> function = input -> 123L; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToLongFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong("123"); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", "123", memoizer.viewCacheForTest().keySet().iterator().next()); Assert.assertEquals("Memoization value does not match expectations", 123L, memoizer.viewCacheForTest().values().iterator().next().longValue()); }
@Test @SuppressWarnings(CompilerWarnings.UNCHECKED) public void shouldUseCallWrappedFunction() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final ToLongFunction<String> function = Mockito.mock(ToLongFunction.class); final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToLongFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong("123"); Mockito.verify(function).applyAsLong("123"); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final ToLongFunction<String> function = input -> 123L; final Function<String, String> keyFunction = Function.identity(); final ConcurrentMapBasedToLongFunctionMemoizer<String, String> memoizer = new ConcurrentMapBasedToLongFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123L, memoizer.applyAsLong("123")); }