GC Rule:
Collect any objects which are not reachable by any part of code. Try the below...
import java.util.*;
class SelfReferencingClassToPreventGC
{
private SelfReferencingClassToPreventGC a;
Object obj = new Vector();
public SelfReferencingClassToPreventGC()
{
a = this; //Cyclic Reference !!!. But this cant stop the object from being garbage collected.
}
public void finalize()
{
System.out.println("Object GCed");
}
}
class SimpleGCThread extends
Thread {
public void run()
{
System.out.println("I will collect the objects which are not reachable by any code");
while (true)
{
System.gc();
try
{
Thread.sleep(100);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
class GCTester {
void aMethod()
{
SelfReferencingClassToPreventGC aObj = new SelfReferencingClassToPreventGC();
}
public static void main (
String args []) {
new GCTester().aMethod();
SimpleGCThread gcThread = new SimpleGCThread();
gcThread.start();
}
}