J2ME Practice: Avoid OutOfMemoryError

Source: Internet
Author: User

For MIDP applications, because of the limited resources on mobile devices, weak CPU computing power, limited memory (from dozens of KB to hundreds of KB, although a handful of high-end handsets have more than 1M of dynamic memory), a small screen size, In order for a MIDP application to run on a variety of different handsets without modification, the program must have the ability to automatically adjust the Run-time parameters according to the system configuration. For example, for a cell phone with very small memory, if you download a larger image from the network, you need to allocate a large buffer, you can cause outofmemoryerror errors, so that the application to terminate directly, which will make users feel overwhelmed, or lose the user's important data.

Therefore, before attempting to allocate a large chunk of memory, first use System.GC () to try to get the garbage collector to release the memory occupied by the unwanted object, and then use the Runtime.getruntime (). Freememory () method to obtain the available memory space. If the free space is too small, give the user an alert prompt with "Insufficient memory to complete the operation" to avoid outofmemoryerror errors as much as possible.

// 示例代码:
System.gc();
int max_size = 102400; // 100KB
int free_size = (int)Runtime.getRuntime().freeMemory();
if(max_size>free_size*2/3) {
// TODO: Alert!
}
else {
byte[] buffer = new byte[max_size];
// TODO: Download image...
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.