Map<E, SoftReference<T>> cache = new ConcurrentHashMap<E, SoftReference<T>>();
我已经 map 声明了一个类似于上面的 map ,我将其用作缓存。
问题是我要在将项目添加到缓存后立即对缓存执行所有操作,而不是稍后。
例如:
cache.add("Username", "Tom");
if(cache.contains("Username"))
返回 true 但
String userName = (String)cache.get("Username")
返回 null。
这只会在很长一段时间后发生。
如果我在将值添加到缓存中几个小时后得到该值,我就可以正确地得到该值。 如果我在很长一段时间后获得该值,比如超过 15-20 小时,我会得到空值。
GC清除SoftReference对象时,key会留在HashMap中吗?这是这种行为的原因吗?
最佳答案
当 SoftReference
的指称时收集垃圾,SoftReference
得到清除,即它的引用字段设置为 null
.
所以不仅键保留在 map 中,关联的值 SoftReference
例如,也保留在 map 中,即使它的引用字段是 null
.
但由于您声明的 Map<E, SoftReference<T>>
之间必须有一层字段和 cache.add("Username", "Tom")
的调用者和 (String)cache.get("Username")
,你没有展示,甚至可能是这一层正确处理的情况。
为了完整起见,正确的实现应该是这样的
final Map<E, SoftReference<T>> cache = new ConcurrentHashMap<>();
/** remove all cleared references */
private void clean() {
cache.values().removeIf(r -> r.get() == null);
}
public void add(E key, T value) {
clean();
cache.put(key, new SoftReference<>(value));
}
public boolean contains(E key) {
clean();
return cache.computeIfPresent(key, (e,r) -> r.get()==null? null: r) != null;
}
public T get(E key) {
clean();
for(;;) {
SoftReference<T> ref = cache.computeIfPresent(key, (e,r) -> r.get()==null? null: r);
if(ref == null) return null;
T value = ref.get();
if(value != null) return value;
}
}
此代码确保在查询时自动删除收集值的映射。此外,尽管不是必需的,clean()
操作删除 map 的所有收集条目,以减少 map 的空间(与 WeakHashMap
内部工作方式相比)。
但请注意,仍然不能保证 cache.contains("Username")
返回 true
, 随后 cache.get("Username")
将返回一个非 null
值(value)。这个问题也被称为 check-then-act 反模式,它可能会失败,因为在检查和后续操作之间,可能会发生并发更新(即使您正在使用缓存只有一个线程,因为垃圾收集可能异步发生),使前面测试的结果过时。
在这方面,contains
操作对于大多数场景是无用的。你必须调用 get
, 接收对一个值的强引用,并继续该引用,如果不是 null
.
关于Java SoftReference 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946705/