Java Programming/Destroying Objects
From Wikibooks, the open-content textbooks collection
| Navigate Classess and Objects topic: |
Unlike in many other object-oriented programming languages, Java performs automatic garbage collection - any unreferenced objects are automatically erased from memory - and prohibits the user from manually destroying objects.
[edit] finalize()
When an object is garbage-collected, the programmer may want to manually perform cleanup, such as closing any open input/output streams. To accomplish this, the finalize() method is used. Note that finalize() should never be manually called, except to call a super class' finalize method from a derived class' finalize method. Also, we can not rely on when the finalize() method will be called. If the java application exits before the object is garbage-collected, the finalize() method may never be called.
protectedvoidfinalize()throwsThrowable {try{ doCleanup(); // Perform some cleanup. If it fails for some reason, it is ignored. }finally{ super.finalize(); //Call finalize on the parent object } }
The garbage-collector thread runs in a lower priority than the other threads. If the application creates objects faster than the garbage-collector can claim back memory, the program can run out of memory.

