() and the implications for
> > garbage collection (gc). Novice java programmers tend to
> > treat gc as magical. Most new users understand to
> > instantiate a listener object, then register this object
> > via remove<>(). The danger is that once they are done with
> > this object they may just let it go assuming it will be
> > gc'ed. Unless they invoke remove<>() their object will
> > never be gc'ed because the event generator's Vector will
> > contain a reference to the object. > >
> >
> > For simple examples like the one in you JavaWorld article
> > in which your Person and AnsweringMachine objects never
> > call removeTelephoneListener() it's not an issue because
> > the program ends right away. But there could be cases in
> > which the program is long-lived, but many listener objects
> > come and go. If the programmer does not explicitly invoke
> > the appropriate remove<>() method, their program will use
> > more and more memory.
> >
> >
> > It's an interaction between the java gc and the 'event
> > generator' idiom that novice programmers might miss.
>
> The forgotten about listeners will not only not get GC'd, but
> they'll keep on receiving events, so they might be doing things
> that cause more harm than just occupying memory. I think
> it is worth having a guideline that says make sure you
> get rid of objects you no longer need, so they can be
> garbage collected. This seems obvious, but as you say, it
> may be non-intuitive to novice programmers exactly how
> objects are being referenced.
> bv
What Brian says is true. I am a novice Java progammer and up to now
gc has been left as magic not only in printed tutorials but most advanced
Java programming books. Online is only slightly better but still
most articles are about the latest API and very few are on the
fundamentals of OOA & OOD that novices need to know and relate to
such basic things as gc. For example I understand the concept of
the Observer pattern and its application in designing the Java API's but
is there a related pattern that can be ascribed to gc? It is still
magic to me.
Thanks to Brian's comment I think I now now why one of my programs
that uses hashtables and vectors extensively crashes.
-H
Replies: