[問題] 關於記憶體管理和finalize方法
剛在書上看到循環參考部分
書上說java如果把物件參考設成null就會被殘存記憶體程序收集掉
書上提供一個技巧說可以避開循環參考
不過我真是有看沒有懂
有人可以解釋一下?
原本程式碼:
class a
{
b b1;
a()
{
b1 = new b();
}
}
class b
{
a a1;
b()
{
a1 = new a();
}
}
public class app
{
public static void main(String[] arg)
{
a obj = new a();
obj = null; //循環參考在此
}
}
技巧程式碼:
class Data
{
public int intdata = 0;
SuperGiantSizeClass sgsc;
Data()
{
intdata = 1;
sgsc = new SuperGiantSizeClass(100000000);
}
protected void finalize()
{
sgsc = null;
}
}
public class app
{
public static void main(String[] arg)
{
Data d = new Data();
d = null;
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.122.138.175
※ 編輯: s35300792001 來自: 122.122.138.175 (02/02 22:04)
推
02/02 23:10, , 1F
02/02 23:10, 1F
推
02/03 08:16, , 2F
02/03 08:16, 2F
→
02/04 03:11, , 3F
02/04 03:11, 3F
推
02/04 09:38, , 4F
02/04 09:38, 4F
※ 編輯: s35300792001 來自: 122.122.138.175 (02/04 22:31)
→
02/04 22:32, , 5F
02/04 22:32, 5F
推
02/05 00:09, , 6F
02/05 00:09, 6F
→
02/07 12:37, , 7F
02/07 12:37, 7F