在下面的示例中,如果垃圾收集器用作weakHashMap 中的键,则垃圾收集器正在销毁一个无用(引用较少)的对象,这没关系.. 但是如果有任何无用的对象作为值,那么垃圾收集器为什么不销毁该对象..
public class WeakHashMapDemo {
public static void main(String[] args) throws InterruptedException{
WeakHashMap whs=new WeakHashMap();
Temp t=new Temp();
Temp t1=new Temp();
Integer x=new Integer(5);
Integer y=6;
whs.put(t,"hemant");
whs.put("hemant", t1);
whs.put(x,"durga");
whs.put(y,"bacon");
System.out.println(whs);
t=null;
t1=null;
x=null;
y=null;
System.gc();
Thread.sleep(2000);
System.out.println(whs);
}
}
临时等级:-
class Temp{
@Override
public String toString() {
return "temp"; //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void finalize() throws Throwable {
System.out.println("finalize() mrthod is called");
}
}
输出
{hemant=temp, 6=bacon, 5=durga, temp=hemant}
finalize() mrthod is called
{hemant=temp, 6=bacon}
根据我的输出应该是: -
{hemant=temp, 6=bacon, 5=durga, temp=hemant}
finalize() mrthod is called
{hemant=null}