Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

What has to be done during destroy() to prevent memory leaks?

843807Feb 12 2007 — edited Feb 14 2007
Hello,

I have written an applet that presents a GUI build with multiple JLabels, JSliders and a JScroller (containing a JPanel).
To work with those I define multiple variables and Event-Listeners (ChangeListeners for the Slider, MouseListeners for the JPanel and JLabels and similar). As a response to a particular Slider-Event a thread is started, which ends by itself. Another Event starts a Timer-Task that is executed only once.
I do not use the keyword "static" anywhere in the applet source code. The various needed classes (for the listener etc) are defined as internal classes.

My problem is that some memory is retained by the java plugin when the user changes the page and the applet is not displayed any longer. The destroy method of the applet is being called - this is shown in the Java Console (with logging enabled) and I also see the effect of some code I put into the destroy() method.

Every time the user opens the page again with the applet in it (and the applet gets initialised), additional memory is allocated by the plugin. After destroying and initialising the applet multiple times during the same browser session, the Java plugin throws a Out-Of-HeapMemory error and the Applet doesn't start.
This is repaired fairly easily by simple restarting the browser, so that the plugin restarts as well; but of course I'd prefer it to work cleaner than that.

So I guess there is a memory leak somewhere. Some object is not destroyed properly or something like that. I am a little confused by this. Shouldn't Java automatically destroy all objects once the applet is being destroyed?
I did add code in the destroy() to remove all Listeners from all my objects, set all ObjectVariables to "null" and called getContentPane().removeall() to get rid of the GUI, but none of these solved my problem.

What are the recommended things to do in the destroy() of an applet? I searched around and read the Java Tutorial about Applets but I couldn't find any information about good programming practice concerning the destroy() in Java Applets.

Can anyone give me some hints about the possible source for this memory leak, or maybe some information about proper things to do when destroying the applet?

Thanks for your help,
Sven
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 14 2007
Added on Feb 12 2007
2 comments
145 views