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