December 22, 2009

Finding memory leaks in Java

There's a popular misconception that Java is immune to memory leaks. That's actually true for C/C++-style memory leaks; the JVM's garbage collector makes it impossible for mere coders to forget a free(). However, as Satish Gupta and Rajeev Palanki of IBM describe, problems can arise when objects that are no longer needed are still referenced by living objects. For example, a programmer might typo a loop and only dereference n-1 of a Collection's elements at a time in a class with numerous instances.

One last-resort trick I learned — on a job interview, actually — for finding memory leaks is to override finalize(). Sure, it's impossible to predict when the method will run, but a few lines of debug info printed to the console twelve percent of the time is better than nothing printed all of the time, especially when you feel like you've already tried everything else.

No comments:

Post a Comment