Fragmentation Problems

A frequent problem for J2ME applications that are running on a KVM implementation without compacting garbage collection is a memory paradox: Runtime.freeMemory() reports lots of free memory, but a memory allocation following immediately fails and causes an OutOfMemoryException.

This issue was especially problematic with early versions of the SUN KVM. The SUN KVM now provides a compacting garbage collector, so this problem seems less important. However, some KVM implementations may not provide a compacting garbage collector for some reason, so you should at least know about the characteristics of the problem.

The reason for the discrepancy between the return value of Runtime.freeMemory() and the ability to allocate a certain block of memory is usually a fragmentation problem: Lots of memory is available, but only in very small pieces. Runtime.freeMemory() reports the total amount of memory available, but the largest continuous block of memory may be much smaller.

The garbage collection for J2SE is usually implemented using a compacting algorithm—all memory blocks that can be reclaimed are compacted to a single large block of memory. In the KVM, free memory blocks are reclaimed, but the compaction step may be omitted for performance and complexity reasons. Thus, a fragmentation problem may occur when a lot of small memory blocks are allocated. Even if most of the small blocks can be reclaimed during garbage collection, the remaining blocks may fragment the free memory into several small pieces.

Although no general solution exists for the fragmentation problem, it may help to call the garbage collector explicitly at some points in the program. Explicit calls of Runtime.gc() will force a garbage collection before all the memory is used up. Thus, only part of the memory is fragmented. New memory allocations are served from the small chunks before the remaining block is touched. Please note that explicit calls to Runtime.gc() may help, but will not do so in all cases, depending on the concrete memory consumption behavior of the application and on the total amount of memory available on the device.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset