ConcurrentMapBasedLongBinaryOperatorMemoizer extends ConcurrentMapBasedMemoizer<KEY, Long> implements LongBinaryOperator { @Override public long applyAsLong(final long left, final long right) { final KEY key = keyFunction.apply(left, right); return computeIfAbsent(key, givenKey -> Long.valueOf(operator.applyAsLong(left, right))) .longValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedLongBinaryOperatorMemoizer(
            final ConcurrentMap<KEY, Long> cache,
            final LongBinaryFunction<KEY> keyFunction,
            final LongBinaryOperator operator); @Override long applyAsLong(final long left, final long right);  }
@Test public void shouldMemoizeOperator() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final LongBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final LongBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedLongBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedLongBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(123, 789); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final LongBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final LongBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedLongBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedLongBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(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, Long> cache = new ConcurrentHashMap<>(); final LongBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final LongBinaryOperator operator = Mockito.mock(LongBinaryOperator.class); final ConcurrentMapBasedLongBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedLongBinaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(123, 789); Mockito.verify(operator).applyAsLong(123, 789); }
@Test public void shouldUseReturnOperatorResult() { final ConcurrentMap<String, Long> cache = new ConcurrentHashMap<>(); final LongBinaryFunction<String> keyFunction = (first, second) -> first + " " + second; final LongBinaryOperator operator = (first, second) -> first + second; final ConcurrentMapBasedLongBinaryOperatorMemoizer<String> memoizer = new ConcurrentMapBasedLongBinaryOperatorMemoizer<>( cache, keyFunction, operator); Assert.assertEquals(912, memoizer.applyAsLong(123, 789)); }