The Artima Developer Community
Sponsored Link

remove() and garbage collection



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


remove() and garbage collection

Posted by Jeff Martin on 21 Aug 1998, 1:28 PM

I think your example should talk about the
remove() 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.


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us