ConcurrentMapBasedIntToLongFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Long> implements IntToLongFunction { @Override public long applyAsLong(final int value) { final KEY key = keyFunction.apply(value); return computeIfAbsent(key, givenKey -> Long.valueOf(function.applyAsLong(value))) .longValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedIntToLongFunctionMemoizer(
            final ConcurrentMap<KEY, Long> cache,
            final IntFunction<KEY> keyFunction,
            final IntToLongFunction function); @Override long applyAsLong(final int value);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<Integer, Long> cache = new ConcurrentHashMap<>(); final IntToLongFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToLongFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong(123); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Integer, Long> cache = new ConcurrentHashMap<>(); final IntToLongFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToLongFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToLongFunctionMemoizer<>( 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().intValue()); Assert.assertEquals("Memoization value does not match expectations", 123L, memoizer.viewCacheForTest().values().iterator().next().longValue()); }
@Test public void shouldUseCallWrappedFunction() { final ConcurrentMap<Integer, Long> cache = new ConcurrentHashMap<>(); final IntToLongFunction function = Mockito.mock(IntToLongFunction.class); final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToLongFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToLongFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsLong(123); Mockito.verify(function).applyAsLong(123); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<Integer, Long> cache = new ConcurrentHashMap<>(); final IntToLongFunction function = input -> 123; final IntFunction<Integer> keyFunction = Integer::valueOf; final ConcurrentMapBasedIntToLongFunctionMemoizer<Integer> memoizer = new ConcurrentMapBasedIntToLongFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123L, memoizer.applyAsLong(123)); }