Monday, March 8, 2010

How to Avoid OutOfMemory Exception in J2ME

Dynamic cache management and performance tuning in J2ME
 
          Each mobile device can handle only a certain amount of cache and if this prescribed amount is exceeded then the dynamic memory blows up resulting in the following scenarios

    * Loss of performance
    * Application hangs your device.
    * Application exits.
    * Application throws an "out of memory"exception.




Never start coding with optimization in mind. Only optimize at the fag end of the project after all code readability is also important an important factor. Intermediate device deployments can also be done to check the device compatibility and get a fair idea of how your application works on the target devices.

Thumb rule for coding J2ME applications is modular programming approach. Never use design patterns
when the target devices are low end devices. We may also think about two code bases one for high end with colorful images etc and another for low end devices with bare minimum functionality.

The above said scenarios may not occur on the emulator
but when ported on to a device could give you sleepless nights. Also this behavior can be differ from device to device. Low end devices are more vulnerable to this problem. Keep this check list ready whenever your application's performance suffers.

    * Use StringBuffer class instead of String for string handling. This is a normal java
      optimization trick.
    * Use minimum number of arrays as possible. Instead of having two different arrays for CITY_ID and CITY_NAME, create a single array with a separator and do parsing within the methods.
    * Push some of the class variables to local variables thus reducing the object memory footprint.
    * Kill the unused Objects, arrays etc especially the image and other multimedia objects after use.
    * Remove RMS if possible.
    * Split Requests-Responses into smaller size in case of web based applications.
    * Use the popular garbage collector call (System.gc()) all over the code.
    * Remove images and other multimedia if possible for lower end devices.
    * Keep the code within the loops as small as possible.
    * Fewer objects you create better. Larger number of object creation and destruction could lead to heap fragmentation.
    * Reuse as many objects as you can. However Pooling is slower than object creation.
    * Thread Synchronization comes with an overhead. Do some work around instead of using synchronization.
    * Avoid double buffering if possible.
    * Reduce try-catch blocks to bare minimum.
    * Close Network Connections after use.
    * Remove float and double calculations if possible.
    * Remove data conversions
      if possible.


This nifty check list is handy for optimization for all devices and varied J2ME applications.

No comments:

Post a Comment