0
考慮下面的代碼:對靜態變量保持強引用的實例變量是否會造成內存泄漏?
public class Leaky {
public static LongLive instance = new LongLive();
static class LongLive {
public void create() {
}
}
static class Victim {
final LongLive factory;
public Victim() {
/** Hold strong reference to static instance */
System.out.println("Create new child..");
factory = instance;
}
@Override
protected void finalize() throws Throwable {
System.out.println("About to get gc-ed?");
super.finalize();
}
}
static void sleep(int sec) {
try {
Thread.sleep(sec * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
for (int i = 0; i < 100; ++i) {
final Victim c = new Victim();
System.gc();
sleep(1);
}
}
}
從我的理解,任何Victim
對象應該從來沒有GC-ED,因爲它保持了強引用instance
對象,只要住在程序運行。但是,我確實看到了打印出的「關於獲取gc-ed」。任何人都可以幫我解釋一下嗎?
你擁有了它倒退,對象將永遠不會被垃圾收集,只要在其他地方有強烈的參考。這個對象本身所引用的內容並不重要。 – Kon
@Kon:啊,明白了。謝謝! – Chan