In an attempt to better control the collection of garbage, I decided it is (I think) advantageous to not nullify objects. Instead, it makes sense to pass them to an ‘storage’ class that can be easily emptied and the System.gc() called. This should limit (I think) the volume of work the garbage collector has to do, and allows you to collect garbage when it suits you, (i.e. between levels or whatever). I don’t know if the code is anygood, just wondering if anyone could comment on its usefulness. Ohh, and if it is useful, feel free to use it
/*
GarbageBin is designed for situations where generating garbage
will affect the performance of the program. It prevents garbage
collection by maintaining references to Object's until the
programmer emptys the bin by nullifying all references and calling
the garbage collector using System.gc()
Usage Example:
GarbageBin bin = new GarbageBin(20);
String forBinning = "This string should be binned";
forBinning = bin.add(forBinning);
...
bin.empty();
*/
public class GarbageBin {
// The bin is simply an array of object refrences
private Object[] theBin;
// We need to know how many items of garbage are in the bin
private int garbageItems;
// Create a new bin to throw garbage in
public GarbageBin() { this(15);}
public GarbageBin(int size) {
theBin = new Object[size];
garbageItems = 0;
}
// Adds garbage to the bin. If the bin is full, what should I do???
public Object add(Object garbage) {
if (garbageItems < theBin.length)
theBin[garbageItems] = garbage;
else
return garbage; // ATM just return the object to itself?
return null;
}
// Empty the bin
public void empty() {
for (int i = 0; i < garbageItems; i++)
theBin[i] = null;
System.gc();
}
}