ConcurrentMapBasedSupplierMemoizer extends ConcurrentMapBasedMemoizer<KEY, VALUE> implements Supplier<VALUE> { @Override public VALUE get() { return computeIfAbsent(keySupplier.get(), input -> supplier.get()); } @SuppressWarnings(CompilerWarnings.NLS)  ConcurrentMapBasedSupplierMemoizer(
            final ConcurrentMap<KEY, VALUE> cache,
            final Supplier<KEY> keySupplier,
            final Supplier<VALUE> supplier); @Override VALUE get();  }
@Test public void shouldMemoizeSuppliedValue() { final ConcurrentMap<String, String> precomputedValues = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final Supplier<String> supplier = () -> "value"; final ConcurrentMapBasedSupplierMemoizer<String, String> memoizer = new ConcurrentMapBasedSupplierMemoizer<>( precomputedValues, keySupplier, supplier); Assert.assertEquals("Memoized value does not match expectations", "value", memoizer.get()); }
@Test public void shouldUseSuppliedKey() { final ConcurrentMap<String, String> precomputedValues = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final Supplier<String> supplier = () -> "value"; final ConcurrentMapBasedSupplierMemoizer<String, String> memoizer = new ConcurrentMapBasedSupplierMemoizer<>( precomputedValues, keySupplier, supplier); Assert.assertTrue("Cache is not empty before memoization", memoizer.viewCacheForTest().isEmpty()); Assert.assertEquals("Memoized value does not match expectations", "value", memoizer.get()); 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.UNCHECKED) public void shouldTriggerOnce() { final ConcurrentMap<String, String> precomputedValues = new ConcurrentHashMap<>(); final Supplier<String> keySupplier = () -> "key"; final Supplier<String> supplier = mock(Supplier.class); given(supplier.get()).willReturn("mocked"); final ConcurrentMapBasedSupplierMemoizer<String, String> memoizer = new ConcurrentMapBasedSupplierMemoizer<>( precomputedValues, keySupplier, supplier); Assert.assertEquals("Memoized value does not match expectations", "mocked", memoizer.get()); Assert.assertEquals("Memoized value does not match expectations", "mocked", memoizer.get()); Assert.assertEquals("Memoized value does not match expectations", "mocked", memoizer.get()); Assert.assertEquals("Memoized value does not match expectations", "mocked", memoizer.get()); verify(supplier, times(1)).get(); }