在 Java 中缓存一组具有 LRU 逐出策略的字符串
Cache a set of strings with LRU eviction policy in Java
我正在尝试以这种方式使用 LRU 逐出策略为一组字符串创建缓存。
private static final Boolean PLACEHOLDER = true;
LoadingCache<String, Boolean> scannedIDsCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, Boolean>() {
@Override
public Boolean load(String key) throws Exception {
return PLACEHOLDER;
}
});
我认为我只使用一个对象作为所有元素的值来保存 space,对吗?您知道其他 space 有效的方法吗?谢谢
不,您没有保存 space。
当一个 JVM* autoboxes a boolean
it calls Boolean.valueOf(boolean)
which returns either Boolean.TRUE
or Boolean.FALSE
which are static final Boolean
fields. It does not create a new Boolean
实例。因此,您定义的 PLACEHOLDER
实际上是对 Boolean.TRUE
的引用并且是多余的。
此外,我不会将Guava的Cache
用于LRU,除非我愿意接受"the cache may evict an entry because it hasn't been used recently or very often"(CacheBuilder.maximumSize(long),强调 已添加)。
如果你想要直接的 LRU,你可以使用 Collections.newSetFromMap(Map)
with LinkedHashMap
:
Set<String> cache = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>() {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > MAX_ENTRIES;
}
});
你在哪里定义MAX_ENTRIES
.
*注意:理论上可能有一些 JVM 实现在自动装箱 boolean
原语时不会在运行时调用 Boolean.valueOf(boolean)
(或类似的东西),但如果这样的实现存在我相当有信心你没有使用它,而且很少有人使用它。来自 Boolean(boolean)
:
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean)
is generally a better choice. It is likely to yield significantly better space and time performance.
我正在尝试以这种方式使用 LRU 逐出策略为一组字符串创建缓存。
private static final Boolean PLACEHOLDER = true;
LoadingCache<String, Boolean> scannedIDsCache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, Boolean>() {
@Override
public Boolean load(String key) throws Exception {
return PLACEHOLDER;
}
});
我认为我只使用一个对象作为所有元素的值来保存 space,对吗?您知道其他 space 有效的方法吗?谢谢
不,您没有保存 space。
当一个 JVM* autoboxes a boolean
it calls Boolean.valueOf(boolean)
which returns either Boolean.TRUE
or Boolean.FALSE
which are static final Boolean
fields. It does not create a new Boolean
实例。因此,您定义的 PLACEHOLDER
实际上是对 Boolean.TRUE
的引用并且是多余的。
此外,我不会将Guava的Cache
用于LRU,除非我愿意接受"the cache may evict an entry because it hasn't been used recently or very often"(CacheBuilder.maximumSize(long),强调 已添加)。
如果你想要直接的 LRU,你可以使用 Collections.newSetFromMap(Map)
with LinkedHashMap
:
Set<String> cache = Collections.newSetFromMap(new LinkedHashMap<String, Boolean>() {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Boolean> eldest) {
return size() > MAX_ENTRIES;
}
});
你在哪里定义MAX_ENTRIES
.
*注意:理论上可能有一些 JVM 实现在自动装箱 boolean
原语时不会在运行时调用 Boolean.valueOf(boolean)
(或类似的东西),但如果这样的实现存在我相当有信心你没有使用它,而且很少有人使用它。来自 Boolean(boolean)
:
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory
valueOf(boolean)
is generally a better choice. It is likely to yield significantly better space and time performance.