以下の例では、weakHashMapのキーとして使用されている場合、ガベージコレクタは無駄な(refrence less)オブジェクトを破棄していますが、ガベージコレクタがそのオブジェクトを破棄していない理由として、なぜガベージコレクタは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}