OutOfMemoryError after a while

Hello,

When let my application running for a long time, I get a java.lang.OutOfMemoryError. So I guess I’m having a memory leak. Do you have any tools to debug it?

Regards,

Hi Marc,

Most of the time Memory Leaks occur when you an instance in a list or an array and forget to remove it. A typical usecase is listeners.
If you have a UI check that any listeners you add in the showNotify is removed in the hideNotify.

Heap dumper

First of all, you can use the heapDumper and analyzer that is provided by the simulator:

  • In your Run configuration, in the Execution tab, make sure that Execute on the Simulator is selected
  • In the Configuration tab got to Simulator->Heap Dumper and check Activate heap dumper

Now a Heap dump will be done after each Garbage Collector (GC) run. You can explicitly call a Garbage Collector with System.gc().

So you can find a path that is likely to generate the memory leak and add a System.gc() call. Then run your application and do the same path over and over.

The heap files are generated in your run output folder/heapDump (by default: [project]/[Main qualifed name]/heapDump).

You can open one with the heap analyzer by double clicking it, you can also compare two of them.
If you were doing the same path over and over, you should have some objects instantiated at the beginning and end of the timeline, but you should not have any at the center (or only weak Ref).

You can follow the hierarchy of an instance to see what is holding it and what it is holding.

For more documentation you can have a look at Help > Help Contents > Heap Analyzer > User Guide

Profiling

The second tool is the profiling library, this library provides some tools to profile your code (Heap, Immortals and thread usage as well as timing).
To use it, add the ivy dependency <dependency org="com.microej.library" name="profiling" rev="[0.0.0-RC0,1.0.0-RC0[" />

Then you can use an Automatic Profiler that will dump the state in the trace regularly or a Sample profiler that can sample specific portions of code and provide information about it (like the duration of a function call or the difference of the memory usage between the beginning and end of it). Some code examples are available In the javadoc.

Regards,

1 Like