我遇到幻像參考時出現問題,當參照物是類內部的字段時。當類對象被設置爲空,字段不會自動通過GC一個類的內部字段不由GC通過幻像參考收集
Controller.java
public class Controller {
public static void main(String[] args) throws InterruptedException
{
Collector test = new Collector();
test.startThread();
Reffered strong = new Reffered();
strong.register();
strong = null; //It doesn't work
//strong.next =null; //It works
test.collect();
Collector.m_stopped = true;
System.out.println("Done");
}
}
Collector.java收集:我有,其登記一個目的是參考隊列並打印出來,當它收集器被收集。
import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.HashMap;
import java.util.Map;
public class Collector {
private static Thread m_collector;
public static boolean m_stopped = false;
private static final ReferenceQueue refque = new ReferenceQueue();
Map<Reference,String> cleanUpMap = new HashMap<Reference,String>();
PhantomReference<Reffered> pref;
public void startThread() {
m_collector = new Thread() {
public void run() {
while (!m_stopped) {
try {
Reference ref = refque.remove(1000);
System.out.println(" Timeout ");
if (null != ref) {
System.out.println(" ref not null ");
}
} catch (Exception ex) {
break;
}
}
}
};
m_collector.setDaemon(true);
m_collector.start();
}
public void register(Test obj) {
System.out.println("Creating phantom references");
//Referred strong = new Referred();
pref = new PhantomReference(obj, refque);
cleanUpMap.put(pref, "Free up resources");
}
public static void collect() throws InterruptedException {
System.out.println("GC called");
System.gc();
System.out.println("Sleeping");
Thread.sleep(5000);
}
}
Reffered.java
public class Reffered {
int i;
public Collector test;
public Test next;
Reffered() {
test= new Collector();
next = new Test();
}
void register() {
test.register(next);
}
}
測試是一個空類。當Reffered對象設置爲null時,我可以看到Refferred類中的「next」字段未被收集。換句話說,當「強」被設置爲空時,「下一個」不被收集。我認爲GC將自動收集「下一個」,因爲當「strong」設置爲空時「next」不再被引用。但是,當「strong.next」設置爲空時,我們認爲收集「下一個」。爲什麼當strong被設置爲null時不會自動收集「next」?
謝謝,@holger。 – GoT