ConcurrentMapBasedIntSupplierMemoizer extends ConcurrentMapBasedMemoizer<KEY, Integer> implements IntSupplier { @Override public int getAsInt() { return computeIfAbsent(keySupplier.get(), input -> Integer.valueOf(supplier.getAsInt())).intValue(); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedIntSupplierMemoizer(
            final ConcurrentMap<KEY, Integer> cache,
            final Supplier<KEY> keySupplier,
            final IntSupplier supplier); @Override int getAsInt();  }
@Test public void shouldMemoizeSuppliedValue() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = () -> 123; final ConcurrentMapBasedIntSupplierMemoizer<String> memoizer = new ConcurrentMapBasedIntSupplierMemoizer<>( cache, keySupplier, supplier); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); }
@Test public void shouldUseSuppliedKey() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = () -> 123; final ConcurrentMapBasedIntSupplierMemoizer<String> memoizer = new ConcurrentMapBasedIntSupplierMemoizer<>( cache, keySupplier, supplier); Assert.assertTrue("Cache is not empty before memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); Assert.assertFalse("Cache is still empty after memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoization key does not match expectations", "key", memoizer.viewCacheForTest().keySet().iterator().next()); }
@Test @SuppressWarnings(CompilerWarnings.BOXING) public void shouldTriggerOnce() { final ConcurrentMap<String, Integer> cache = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final IntSupplier supplier = mock(IntSupplier.class); given(supplier.getAsInt()).willReturn(123); final ConcurrentMapBasedIntSupplierMemoizer<String> memoizer = new ConcurrentMapBasedIntSupplierMemoizer<>( cache, keySupplier, supplier); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); Assert.assertEquals("Memoized value does not match expectations", 123, memoizer.getAsInt()); verify(supplier, times(1)).getAsInt(); }