ConcurrentMapBasedLongUnaryOperatorMemoizer extends ConcurrentMapBasedMemoizer<KEY, Long> implements LongUnaryOperator { @Override public long applyAsLong(final long operand) { final KEY key = keyFunction.apply(operand); return computeIfAbsent(key, givenKey -> Long.valueOf(operator.applyAsLong(operand))) .intValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedLongUnaryOperatorMemoizer(
            final ConcurrentMap<KEY, Long> cache,
            final LongFunction<KEY> keyFunction,
            final LongUnaryOperator operator); @Override long applyAsLong(final long operand);  }
@Test public void shouldMemoizeOperator() { final ConcurrentMap<Long, Long> cache = new ConcurrentHashMap<>(); final LongUnaryOperator operator = input -> input; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongUnaryOperatorMemoizer<Long> memoizer = new ConcurrentMapBasedLongUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(123L); }
@Test public void shouldUseSetCacheKeyAndValue() { final ConcurrentMap<Long, Long> cache = new ConcurrentHashMap<>(); final LongUnaryOperator operator = input -> input; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongUnaryOperatorMemoizer<Long> memoizer = new ConcurrentMapBasedLongUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(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", 123L, memoizer.viewCacheForTest().values().iterator().next().longValue()); }
@Test public void shouldUseCallWrappedOperator() { final ConcurrentMap<Long, Long> cache = new ConcurrentHashMap<>(); final LongUnaryOperator operator = Mockito.mock(LongUnaryOperator.class); final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongUnaryOperatorMemoizer<Long> memoizer = new ConcurrentMapBasedLongUnaryOperatorMemoizer<>( cache, keyFunction, operator); memoizer.applyAsLong(123L); Mockito.verify(operator).applyAsLong(123L); }
@Test public void shouldUseReturnOperatorResult() { final ConcurrentMap<Long, Long> cache = new ConcurrentHashMap<>(); final LongUnaryOperator operator = input -> input; final LongFunction<Long> keyFunction = Long::valueOf; final ConcurrentMapBasedLongUnaryOperatorMemoizer<Long> memoizer = new ConcurrentMapBasedLongUnaryOperatorMemoizer<>( cache, keyFunction, operator); Assert.assertEquals(123L, memoizer.applyAsLong(123L)); }