जावा में एक कक्षा कचरा-संग्रहित हो सकती है जब कुछ भी इसका संदर्भ नहीं देता है। सबसे सरल सेटअप में यह कभी नहीं होता है, लेकिन ऐसी स्थितियां हैं जहां यह हो सकती है।
जब कोई भी उन लोगों में से सत्य हैं , तो ClassLoader
और लोड किए गए सभी वर्ग जीसी के लिए योग्य हैं।
यहाँ एक का निर्माण उदाहरण है कि व्यवहार का प्रदर्शन करना चाहिए (गलत व्यवहारों से भरा हुआ!):
एक निर्देशिका में बाईटकोड फ़ाइल GCTester.class
बनाएँ (पैकेज नहीं!) x
। यह स्रोत कोड है:
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Field;
public class TestMe {
public static void main(String[] args) throws Exception {
System.out.println("in main");
testGetObject();
System.out.println("Second gc() call (in main)");
System.gc();
Thread.sleep(1000);
System.out.println("End of main");
}
public static void testGetObject() throws Exception {
System.out.println("Creating ClassLoader");
ClassLoader cl = new URLClassLoader(new URL[] {new File("./x").toURI().toURL()});
System.out.println("Loading Class");
Class<?> clazz = cl.loadClass("GCTester");
System.out.println("Getting static field");
Field field = clazz.getField("INSTANCE");
System.out.println("Reading static value");
Object object = field.get(null);
System.out.println("Got value: " + object);
System.out.println("First gc() call");
System.gc();
Thread.sleep(1000);
}
}
TestMe
चल रहा है इस (या समान) उत्पादन का उत्पादन होगा:
in main
Creating ClassLoader
Loading Class
Getting static field
Reading static value
[email protected] created
Got value: [email protected]
First gc() call
Second gc() call (in main)
[email protected] finalized
End of main
में
public class GCTester {
public static final GCTester INSTANCE=new GCTester();
private GCTester() {
System.out.println(this + " created");
}
public void finalize() {
System.out.println(this + " finalized");
}
}
फिर x
की पेरेंट निर्देशिका में एक वर्ग TestMe
बनाने पिछली पंक्ति में दूसरा हम देखते हैं कि GCTester
उदाहरण को अंतिम रूप दिया गया है, जिसका अर्थ केवल वर्ग (और ClassLoader
) कचरा संग्रह के लिए पात्र हैं।
स्रोत
2010-03-12 14:20:15
आपको यह विषय उपयोगी हो सकता है: http://stackoverflow.com/questions/453023/are-static-fields-open-for-garbage-collection –
यह भी एक है: "जावा क्लासलोडर कब और कैसे चिह्नित किया जाता है कचरा संग्रह के लिए? " http://stackoverflow.com/questions/2344964/when-and-how-is-a-java-classloader-marked-for-garbage-collection – ewernli