Freeing Unused Variables and Resources

The Java garbage collection mechanism usually frees unused objects automatically. “Unused” from the point of view of the garbage collector means that the objects are not referenced from somewhere else. If objects are no longer needed in a program, but are still referenced by a variable or indirectly by another object, the garbage collector can't determine that the object can be removed, and the corresponding memory is not reclaimed. Thus, if an object is allocated and then no longer needed, but the variable holding the object is still in the valid scope, it may make sense to set the variable to null explicitly. For example, if a buffer is allocated at the beginning of a method, but then no longer needed in the method, the garbage collector cannot reclaim the buffer because the variable still points to the buffer. If the variable is explicitly set to null, the buffer is no longer referenced and can be reclaimed by the garbage collection.

For J2ME, it is also very important to always dispose resources such as record stores or connections when they are no longer needed. J2ME does not support finalization, which means that system resources cannot be closed automatically during garbage collection. Thus, if the reference to a system resource is removed without closing the resource, the resource will stay allocated until system cleanup, when the program is terminated completely.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset