Detecting Memory Leaks in Java

Aus SDQ-Wiki

Although memory allocation and deallocation is much simpler in Java, memory leaks can still occur. An article at IBM developerworks on memory leaks gives a good introduction on the topic, even though the article is old.

How to find memory leaks in the PCM / Eclipse applications

Analyse heap dump

The simplest way to find memory leaks is to analyse a heap dump of your program.

Using JProfiler

With JProfiler, analysing a heap dump is even simpler.

  • Install JProfiler and integrate it in your Eclipse.
  • Run a profiled version of the PCM bench/ your application
  • Do what has cause memory leaks before (e.g. running the simulation).
  • Watch the memory allocation in the VM telemetry view.
  • Run the GC manually to see whether the memory can be freed again.
  • If still a lot of memory has been allocated that you think should not be freed by now, do a heap dump. In JProfiler, click Heap Walker and take a snapshot.
  • You see which objects are in the memory.
    • Sort the objects by total size or instance count. If you have run the leaking code regions long enough before, the upper entry is probably your problem.
    • You may already detect the cause here, if one of your objects is allocated often.
  • If the problem is with too many instances of Java standard library objects (e.g. Double or String), analyse where they are hold:
    • To see where the objects that are allocated so often are kept, click in References below and select References -> cumulated incoming references. Here, you can see the Objects that refer to the problematic objects, and you can probably detect which of your classes holds too many objects.

Limitations

Not all memory leaks can be found this way, some require monitoring the memory allocation to find the real cause.