Avoiding memory leaks in Java _Much of these notes are from Jean Bovet, former USF student_ 1) Delegate Most of the time a class register itself as a delegate and forget to unregister itself (when it is about to close - for example, a window can be a delegate of a menu bar and should unregister itself when closing). Most of the UI examples lacks the "closing" part which is extremely important because the class holding the delegate will have a strong reference to the delegate. 2) Anonymous class keep a reference to the enclosing class Make sure to unregister all anonymous class. For example, ActionListener are often added but not removed. A few words about fixing these issues: To detect and fix the memory leak, use the appropriate tool for that. For example, JProfiler. In JProfiler, the best friend for memory leak is the Heap Walker. Here are some steps describing how to remove some memory leak: - run your program in JProfiler. - perform the operation having a memory leak - when the operation finishes, go back to JProfiler and take a snapshot with Heap Walker: the content of the heap is displayed. Look for any leaking objects belonging to your code (or taking a lot of memory or having a lot of instances - this depends on the kind of objects/operation you are debugger). - use JProfiler to display the graph of incoming/outgoing references to that object. At this point, you can already see which objects are referencing your "leaking" object. You can also use the "Show path to GC root" to see the whole reference chain to the garbage collector - useful to see all the objects involved in the chain of reference. - with a little bit of time, you can easily detect which references should be removed. - fix the code and repeat these steps.