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