[問題] 關於記憶體管理和finalize方法

看板java作者 (小朱)時間17年前 (2009/02/02 22:02), 編輯推噓4(403)
留言7則, 4人參與, 最新討論串1/1
剛在書上看到循環參考部分 書上說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
應該是想強調finalize的使用方法吧,書上應該都有說才是..
02/03 08:16, 2F

02/04 03:11, , 3F
回一樓...書上的技巧就是我打上的code...
02/04 03:11, 3F

02/04 09:38, , 4F
作者不可能只給 code 不解釋技巧在那吧? 如果是, 那很糟.
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
書名java 2 Black Book徹底研究
02/07 12:37, 7F
文章代碼(AID): #19Xlp-Op (java)