TheFreeSite.com!

Monday, July 28, 2008

The housekeeping dilemma:who should clean up?

Each object requires resources in order to exist, most notably memory. When an object is no
longer needed it must be cleaned up so that these resources are released for reuse. In simple
programming situations the question of how an object is cleaned up doesn’t seem too
challenging: you create the object, use it for as long as it’s needed, and then it should be
destroyed. It’s not too hard, however, to encounter situations in which the situation is more
complex.
Suppose, for example, you are designing a system to manage air traffic for an airport. (The
same model might also work for managing crates in a warehouse, or a video rental system,
or a kennel for boarding pets.) At first it seems simple: make a collection to hold airplanes,
then create a new airplane and place it in the collection for each airplane that enters the airtraffic-
control zone. For cleanup, simply delete the appropriate airplane object when a plane
leaves the zone.
But perhaps you have some other system to record data about the planes; perhaps data that
doesn’t require such immediate attention as the main controller function. Maybe it’s a
record of the flight plans of all the small planes that leave the airport. So you have a second
collection of small planes, and whenever you create a plane object you also put it in this
collection if it’s a small plane. Then some background process performs operations on the
objects in this collection during idle moments.
Now the problem is more difficult: how can you possibly know when to destroy the objects?
When you’re done with the object, some other part of the system might not be. This same
problem can arise in a number of other situations, and in programming systems (such as
Chapter 1: Introduction to Objects 55
C++) in which you must explicitly delete an object when you’re done with it this can
become quite complex.6
With Java, the garbage collector is designed to take care of the problem of releasing the
memory (although this doesn’t include other aspects of cleaning up an object). The garbage
collector “knows” when an object is no longer in use, and it then automatically releases the
memory for that object. This, combined with the fact that all objects are inherited from the
single root class Object and that you can create objects only one way, on the heap, makes
the process of programming in Java much simpler than programming in C++. You have far
fewer decisions to make and hurdles to overcome.

0 comments:

Tell Me Doubts In Java