Roedy Green said:
:On 24 Apr 2004 07:44:19 -0700, (e-mail address removed) (aruna) wrote or
:quoted :
:
:>How memory leaks in java. What are the different ways in which
:>memory can leak. I know of tools which eliminate the leaks,
:>but I want to know what causes leaks, so that I can practice
:>not to write a program which leaks memory?
:
:see
http://mindprod.com/jgloss/packratting.html
:
:Strictly speaking, you can't have a memory leak in Java, at least not
:in the same sense you can in C++.
Sun would have us believe that it's "theoretically" impossible to get a
memory leak. But that's flatly not true. It can happen in complex
objects beyond just Swing components. Been there, done that. And there
are commercial tools aimed at helping find leaks so that you can resolve
them. We happen to use OptimizeIt, now sold by Borland.
The garbage collection system truly is an improvement over what C++
users have had to do, IMO. And many common references will in fact get
cleaned up. We had some concerns about whether a HashMap, ArrayList or
Vector, for instance, needed to be cleared before it would get
collected. Our testing showed that it got collected sooner if we
cleared the contents, but that it would still get collected even if we
didn't. I rather suspect that simple "circular" references, where two
objects refer to each other, but neither can be found by my code, also
get collected properly, though we weren't concerned about that (that is,
after all, one of the strengths of Java). But we fought a long, hard
battle over much more complex references eating up our memory, so we
eventually added dispose() methods in a number of our own complex
(non-GUI) classes to resolve the problem by ensuring that our references
got zapped, or caused subordinate objects to do their own dispose()
kinds of work.
The glossary reference to Threads brings up another area I stumbled
across, too. I worked for a long time trying to figure out why my
program's JWindow used at startup as a splash screen never got
collected. Then I finally discovered it was Thread related. The old
rule about quitting the JVM after all non-daemon Threads have finished
was the clue, but it took a while for me to add things up. My app's
main startup method displayed that JWindow, then built and displayed the
main app JFrame, then closed the JWindow. All attempts to call
dispose() on it, to remove its components, everything failed -- until I
realized that it left a Thread behind where my main() method was that
caused the entire problem. So now, I create the window and build it up,
but the calls to show and hide it are both done via Runnable. And it
gets collected fairly soon after! Lesson learned.
= Steve =