ConcurrentMapBasedLongToDoubleFunctionMemoizer extends ConcurrentMapBasedMemoizer<KEY, Double> implements LongToDoubleFunction { @Override public double applyAsDouble(final long value) { final KEY key = keyFunction.apply(value); return computeIfAbsent(key, givenKey -> Double.valueOf(function.applyAsDouble(value))) .doubleValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedLongToDoubleFunctionMemoizer(
            final ConcurrentMap<KEY, Double> cache,
            final LongFunction<KEY> keyFunction,
            final LongToDoubleFunction function); @Override double applyAsDouble(final long value);  }
@Test public void shouldMemoizeFunction() { final ConcurrentMap<Long, Double> cache = new ConcurrentHashMap<>(); final LongToDoubleFunction function = input -> 123; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongToDoubleFunctionMemoizer<Long> memoizer = new ConcurrentMapBasedLongToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(123); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Long, Double> cache = new ConcurrentHashMap<>(); final LongToDoubleFunction function = input -> 123; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongToDoubleFunctionMemoizer<Long> memoizer = new ConcurrentMapBasedLongToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(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", 123D, memoizer.viewCacheForTest().values().iterator().next().doubleValue(), 0.0D); }
@Test public void shouldUseCallWrappedFunction() { final ConcurrentMap<Long, Double> cache = new ConcurrentHashMap<>(); final LongToDoubleFunction function = Mockito.mock(LongToDoubleFunction.class); final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongToDoubleFunctionMemoizer<Long> memoizer = new ConcurrentMapBasedLongToDoubleFunctionMemoizer<>( cache, keyFunction, function); memoizer.applyAsDouble(123); Mockito.verify(function).applyAsDouble(123); }
@Test public void shouldUseReturnFunctionResult() { final ConcurrentMap<Long, Double> cache = new ConcurrentHashMap<>(); final LongToDoubleFunction function = input -> 123; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongToDoubleFunctionMemoizer<Long> memoizer = new ConcurrentMapBasedLongToDoubleFunctionMemoizer<>( cache, keyFunction, function); Assert.assertEquals(123D, memoizer.applyAsDouble(123), 0.0D); }