我在我的应用程序中使用番石榴缓存来提高性能。我使用LoadingCache中的putAll API 在缓存中插入了 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 返回缓存中的近似条目数。
任何人都可以提供有关 850 到 9467 如何作为近似值的见解吗?