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