I'm having a problem understanding your question, but let me try and see if I'm on track. 1) How do you know when the objects taking up memory have been reclaimed? 2) How does garbage collection happen? 1) Once you aren't referencing objects with reference variables they are elgible for garbage collection. Garbage collection, however, is done at the convenience of the JVM. It cannot be forced, but can be requested. You can override the finalize method that is called when objects are being reclaimed. However, there's always the possibility that the object will become ineligible for garbage collection at that time, and finalize may never be called again. In that case, you wouldn't be sure when the memory is actually reclaimed. You shouldn't really need to care about it though, IMO. I just create the darn things and when they're gone, they're gone. 2) Garbage collection can be requested by some function that I've never used. SomeClass.gc() -- maybe System.gc .. beats me. (Somebody correct me). At that point, garbage collection may happen, or it may happen later. I hope that matches your questions closely -- if not, go ahead and explain more.
You have it backwards. When an object is garbage collected, finalize MAY be called. There is no guarantee that it will be. One can request that garbage collection is performed by invoking java.lang.System.gc(), but again, there is no guarantee that garbage collection will take place. It is a Bad Idea to invoke System.gc() since it diverts valuable processing time away from getting the user's work done.
Furthermore, you never call finalize yourself. It is called by the JVM during the object's lifetime at some point. You can call finalize yourself, but that would just be silly (in most cases you have no reason to).
By far the safest policy regarding garbage collection is to ignore it. You can't control it, and you can't rely on it doing anything predictable. If you are careful to not leave references around to objects you no longer need, you probably will never have to think about it. For example, I work on a system that helps customer service people handle phone calls. During the course of a phone call we create a lot of stuff in memory. At the end of the call we clear out all the variables and vectors and such. If we forget to remove something then every phone call adds more objects and by the end of the work day the user is out of memory.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
posted 14 years ago
Thanks all guys to help me, I got it now. Sincerely, Sophie lin