|
|
|
Advertisement
|
Summary
This installment of the Design Techniques column discusses the design guidelines that pertain to the end of an object's life. I give an overview of the rules of garbage collection, discuss finalizers, and suggest ways to design objects such that finite resources aren't monopolized.
Three months ago, I began a mini-series of articles about designing objects with a discussion of design principles that focused on proper initialization at the beginning of an object's life. In this Design Techniques article, I'll be focusing on the design principles that help you ensure proper cleanup at the end of an object's life.
Why clean up?
Every object in a Java program uses computing resources that are
finite. Most obviously, all objects use some memory to store their
images on the heap. (This is true even for objects that declare no
instance variables. Each object image must include some kind of pointer
to class data, and can include other implementation-dependent
information as well.) But objects may also use other finite resources
besides memory. For example, some objects may use resources such as
file handles, graphics contexts, sockets, and so on. When you design an
object, you must make sure it eventually releases any finite
resources it uses so the system won't run out of those resources.
Because Java is a garbage-collected language, releasing the memory associated with an object is easy. All you need to do is let go of all references to the object. Because you don't have to worry about explicitly freeing an object, as you must in languages such as C or C++, you needn't worry about corrupting memory by accidentally freeing the same object twice. You do, however, need to make sure you actually release all references to the object. If you don't, you can end up with a memory leak, just like the memory leaks you get in a C++ program when you forget to explicitly free objects. Nevertheless, so long as you release all references to an object, you needn't worry about explicitly "freeing" that memory.
Similarly, you needn't worry about explicitly freeing any constituent objects referenced by the instance variables of an object you no longer need. Releasing all references to the unneeded object will in effect invalidate any constituent object references contained in that object's instance variables. If the now-invalidated references were the only remaining references to those constituent objects, the constituent objects will also be available for garbage collection. Piece of cake, right?
|
Sponsored Links
|