3

JavaCachingWithGuavaは、キャッシングをオフにする標準的な方法はmaximumSize=0を設定することであることを示唆しています。ただし、以下のテストに合格することを期待しています。

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)));
    }
}

つまり、キャッシュをオフにすると、常にキャッシュ ミスが発生します。

ただし、テストは失敗します。私の解釈は間違っていますか?

4

1 に答える 1

6

このメソッドは、への呼び出しを無視して、デフォルト設定でnewBuilder新しいインスタンスを構築します。ただし、特定の最大サイズでを作成したいとします。したがって、への呼び出しを削除します。デフォルト設定でスペックを取得するのではなく、一致するスペックを取得するには、への呼び出しを使用する必要があります。CacheBuilderfromCacheBuildernewBuiderbuildCacheBuilder

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();
                    }
                });
于 2012-12-07T12:52:57.490 に答える