Reputation: 455
JavaCachingWithGuava suggests the canonical way to turn off caching is to set maximumSize=0. However, I'd expect the test below to pass:
public class LoadingCacheTest {
private static final Logger LOG = LoggerFactory.getLogger(LoadingCacheTest.class);
LoadingCache<String, Long> underTest;
@Before
public void setup() throws Exception {
underTest = CacheBuilder.from("maximumSize=0").newBuilder()
.recordStats()
.removalListener(new RemovalListener<String, Long>() {
@Override
public void onRemoval(RemovalNotification<String, Long> removalNotification) {
LOG.info(String.format("%s cached value %s for key %s is evicted.", removalNotification.getCause().name(), removalNotification.getValue(), removalNotification.getKey()));
}
})
.build(new CacheLoader<String, Long>() {
private final AtomicLong al = new AtomicLong(0);
@Override
public Long load(@NotNull final String key) throws Exception {
LOG.info(String.format("Cache miss for key '%s'.", key));
return al.incrementAndGet();
}
});
}
@Test
public void testAlwaysCacheMissIfCacheDisabled() throws Exception {
String key1 = "Key1";
String key2 = "Key2";
underTest.get(key1);
underTest.get(key1);
underTest.get(key2);
underTest.get(key2);
LOG.info(underTest.stats().toString());
Assert.assertThat(underTest.stats().missCount(), is(equalTo(4L)));
}
}
That is, turning off the cache always results in a cache miss.
The test fails, though. Is my interpretation incorrect?
Upvotes: 3
Views: 3447
Reputation: 14728
The method newBuilder
constructs a new CacheBuilder
instance with default settings, ignoring the call to from
. However, you want to construct a CacheBuilder
with a specific maximum size. So, remove the call to newBuider
. You should use your call to build
to get a CacheBuilder
matching your spec rather than getting one with default settings:
underTest = CacheBuilder.from("maximumSize=0")
.recordStats()
.removalListener(new RemovalListener<String, Long>() {
@Override
public void onRemoval(RemovalNotification<String, Long> removalNotification) {
LOG.info(String.format("%s cached value %s for key %s is evicted.", removalNotification.getCause().name(), removalNotification.getValue(), removalNotification.getKey()));
}
})
.build(new CacheLoader<String, Long>() {
private final AtomicLong al = new AtomicLong(0);
@Override
public Long load(@NotNull final String key) throws Exception {
LOG.info(String.format("Cache miss for key '%s'.", key));
return al.incrementAndGet();
}
});
Upvotes: 6