ConcurrentMapBasedIntBinaryOperatorMemoizer extends ConcurrentMapBasedMemoizer<KEY, Integer> implements IntBinaryOperator { @Override public int applyAsInt(final int left, final int right) { final KEY key = keyFunction.apply(left, right); return computeIfAbsent(key, givenKey -> Integer.valueOf(operator.applyAsInt(left, right))) .intValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedIntBinaryOperatorMemoizer(
            final ConcurrentMap<KEY, Integer> cache,
            final IntBinaryFunction<KEY> keyFunction,
            final IntBinaryOperator operator); @Override int applyAsInt(final int left, final int right);  }
@Test public void shouldMemoizeOperator() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final IntBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final IntBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedIntBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedIntBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123, 789); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final IntBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final IntBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedIntBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedIntBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123, 789); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", "123 789", memoizer.viewCacheForTest().keySet().iterator().next()); Assert.assertEquals("Memoization value does not match expectations", 912, memoizer.viewCacheForTest().values().iterator().next().intValue()); }
@Test public void shouldUseCallWrappedOperator() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final IntBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final IntBinaryOperator operator = Mockito.mock(IntBinaryOperator.class); final ConcurrentMapBasedIntBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedIntBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsInt(123, 789); Mockito.verify(operator).applyAsInt(123, 789); }
@Test public void shouldUseReturnOperatorResult() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final IntBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final IntBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedIntBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedIntBinaryOperatorMemoizer<>( cache, keyFunction, operator); Assert.assertEquals(912, memoizer.applyAsInt(123, 789)); }