有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Guava缓存大小方法不返回缓存中的实际条目数

我在应用程序中使用guava缓存来提高性能。我在LoadingCache中使用putAllAPI在缓存中插入了850个条目。我配置的最大缓存大小为20K个条目。我正在使用测试类TestCacheSize测试缓存大小:

public class MetadataCacheKey{
    // implementation
}

public class Metadata{
    // implementation
}

public class MetadataCacheLoader extends CacheLoader<MetadataCacheKey, Optional<Metadata>> {
    /**
     * Guava cache does not support null values in cache. So null response from metadata source is wrapped in Optional
     * and loaded in cache. This reduces look ups for keys which are not present in source.
     */
    @Override
    public Optional<Metadata> load(@NonNull MetadataCacheKey key) throws Exception {
        return Optional.fromNullable(loadMetadataFromSource(key));
    }
    private Metadata loadMetadataFromSource(MetadataCacheKey key) {
        // implementation
    }
}

public class TestCacheSize {
    public static void main(String[] args) {
        LoadingCache<MetadataCacheKey, Optional<Metadata>> metadataCache = CacheBuilder.from(
                "expireAfterWrite=4h,maximumSize=20000").build(new MetadataCacheLoader());
        metadataCache.putAll(getAllMetadataFromDb());
        System.out.println(metadataCache.size());         // output is 9467 (amusing)
        System.out.println(metadataCache.asMap().size()); // output is 850  (as expected)
    }
    // assume always returns map with size equal to 850
    private static Map<MetadataCacheKey, Optional<Metadata>>  getAllMetadataFromDb(){
        return new HashMap<MetadataCacheKey, Optional<Metadata>>();
    }
}

从缓存大小的javadocs开始:

size returns approximate number of entries in cache.

有人能给出850到9467的近似值吗


共 (0) 个答案