In a nutshell there are 3 things you can do to facilitate garbage collection:
1. When you�re done with a reference to an object, set it to null. This way that object is marked for garbage collection.
2. Implement the finalize method for your complex objects. Here you could set all object references that this object used to null. The finalizer is the last thing that is called before the garbage collector reclaims the memory for the object. By the way, when one implements a finalize method, one is overriding the finalize method from the superclass Object.
3. You can suggest that the gc be ran with: System.gc() or Runtime.getRuntime.gc(). Java does not guarantee which object's finalizer will execute first. Garbage collection can be CPU intensive.
Hope this helps. Let me know if you have more questions.
Additional information:
Garbage collector is a low priority daemon thread (one that runs for the benefit of other threads.) The java language specification strangely, doesn't lay down the law on how garbage is to be collected. This way every implementer of a JVM is allowed to pursue the optimal method of gc.
Hope this helps.
Originally posted by Alex Guo:
I am wondering what I shall do if I want to collect garbage on time so that the application won't run out of memory. I think it's very important for a software product to sustain stress test.
In the methods, do I need to set variables to null before leaving? or those variables are automatically discarded and the corresponding referenced objects will be garbage collected(later)? Is there any other thing I shall do for this?
Thanks!