I'm trying to create my own pattern (or something similar to a pattern I guess) where objects that are anonymously instantiated can still be referenced, but I'm getting weird memory results. It seems as if the free memory is decreasing when it should be increasing--
import java.util.ArrayList;
public class SelfTracker{
private final static ArrayList<SelfTracker> track = new ArrayList<SelfTracker>(0);
private int index = 0;
private static int trackCount = 0;
public SelfTracker(){
index = trackCount++;
track.add(this);
}
/**
* Shortcut way of printing the data in the track
*/
public static void printData(){
System.out.println(track);
}
/**
* Clears the tracker, and then calls the garbage
* collector to remove the (supposedly) untracked
* objects from being used in heap memory.
*/
public static void releaseAll(){
track.clear(); // Assuming that the references of the ArrayList will be pointint to null
Runtime.getRuntime().gc(); // gets the current Runtime and attempts to garbage-collect unpointed references
// (not reliable)
}
/**
* Simply prints a message when this method is called.
*/
@Override protected void finalize() throws Throwable{
System.out.println("Releaseing object: " + this);
super.finalize();
}
/**
* Just overriding the toString method in the base class
*/
@Override public String toString(){
return "SelfTracker at address: " + super.toString().toUpperCase() +
"\n with index: " + index;
}
public static void main(String... args){
Runtime rt = Runtime.getRuntime(); // getting a handle on the current runtime for this JVM
rt.gc(); // for accuracy
System.out.println(rt.freeMemory() + " / " + rt.totalMemory()); // printing the freeMEM/totalMEM
new SelfTracker(); // no other reference other than static track
new SelfTracker(); // ditto
new SelfTracker(); // ditto
System.out.println(rt.freeMemory() + " / " + rt.totalMemory()); // oddly no change in memory?
SelfTracker.printData(); // printing the data in the track
SelfTracker.releaseAll(); // I'm trusting the definition of ArrayList's "clear" to set its list-references to null
/*
Assumption - nothing was pointing to the objects after they were cleared from ArrayList.
They should be garbage collected.
*/
System.out.println(rt.freeMemory() + " / " + rt.totalMemory()); // free memory decreases!
}
}