我目前對一個沒有調用finalize()
方法的類的對象存在問題,儘管只存儲在作爲值的ConcurrentHashMap
中,而對象的UUID
作爲鍵地圖。儘管WeakReference沒有調用finalize()方法
這裏是我創建了一個例子(它不是在我的實際項目中使用的一個,但這個例子中也沒有調用的對象finalize()
方法。
TestMain.class //主類處理HashMap中
public class TestMain {
public static ConcurrentHashMap<String, WeakReference<Test>> map = new ConcurrentHashMap<String, WeakReference<Test>>();
public static void main(String args[]) {
map.put("Key1", new WeakReference<Test>(new Test("test 1", 2))); //This "Test" Object shouldn't be accessible anywhere besides the HashMap anymore, and therefore I want it to be "finalized" by the garbage collector.
System.out.println("DONE");
}
}
的Test.class //對象類
public class Test {
public String string;
public int intt;
public Test(String string, int intt) {
this.string = string;
this.intt = intt;
}
@Override
protected void finalize() throws Throwable {
System.out.println("FINALIZED TEST CLASS: " + string);
super.finalize();
}
}
當運行的主要方法,所有的被印刷爲 「DONE」 時我人口會d「FINALIZED TEST CLASS:Test 1」也可以在此之前打印。我的代碼有什麼問題,或者我誤解finalize()
的工作原理?
另外,我想這個工作,我解釋一下,因爲我需要與finalize()
方法的對象從「地圖」 Map
從記憶中抹去一樣會有我的項目運行過程中產生的對象的幾百持續時間,所以我希望不再使用的對象被清除,爲更多新對象騰出空間。
編輯:我看到互聯網上的其他地方,人們說程序可能在垃圾回收器有機會處理上述對象之前終止。因此,我試圖通過添加一個簡單的while(true){}
循環來讓我的程序不終止,並等待了幾分鐘,但仍然沒有看到該對象正在「完成」的消息。
任何幫助非常感謝,謝謝。
無法保證finalize方法將被稱爲 – Pragnani
@PragnaniKinnera那麼,我將如何手動處理這些對象後,他們不能在其他地方訪問?我現在很困惑 –
@C_Beth這不是你的工作,GC會照顧到這一點。當你嘗試自己做這件事會引起額外的煩惱 – Pragnani