【发布时间】:2026-01-17 06:50:01
【问题描述】:
首先我想澄清我对WeakReference 的理解,因为以下问题取决于相同的问题。
static void test() {
Person p = new Person();
WeakReference<Person> person = new WeakReference<>(p);
p = null;
System.gc();
System.out.println(person.get());
System.out.println(person);
}
static class Person {
String name;
}
static class PersonMetadata {
String someData;
public PersonMetadata(String met) {
someData = met;
}
}
上面代码的输出是
null
java.lang.ref.WeakReference@7852e922
这意味着虽然实际的 person 对象在 GC 运行后被垃圾回收,但内存中存在一个 WeakReference<Person> 类的对象,此时它不指向任何东西。
现在考虑到上述理解是正确的,我对WeakHashMap<K,V> 的工作原理感到困惑。在下面的代码中
public static void main(String[] args) {
Person p = new Person();
p.name = "John";
WeakHashMap<Person, PersonMetadata> map = new WeakHashMap<>();
PersonMetadata meta = new PersonMetadata("Geek");
map.put(p, meta);
p = null;
System.gc();
if (map.values().contains(meta)) {
System.out.println("Value present");
} else {
System.out.println("Value gone");
}
}
static class Person {
String name;
}
static class PersonMetadata {
String someData;
public PersonMetadata(String met) {
someData = met;
}
}
输出: Value gone
现在的问题就是说WeakHashMap<K,V>中的键是弱引用,这意味着在上面的代码中,当p变成@ 987654331@ 实际对象可以被垃圾收集,因为没有更多对该对象的强引用,但是 PersonMetadata 类的对象的值如何被垃圾收集作为第一个代码证明WeakReference 类的对象即使实际对象已被回收,也不会被垃圾回收。
【问题讨论】:
-
我已经解释了清理弱引用回答this question的方法。
标签: java collections garbage-collection weak-references weakhashmap