Saturday, April 24, 2010

Avoiding OutOfMemoryError

Some Java ME applications load all their resources from its own jar file, but other apps load resources dinamically, for example,
from a network connection.

My Books application can open text files using an
Open File Dialog I have created.
But what happens if a file is too big to open?

If the Java Virtual Machine raises an Exception current version (1.3)
will show an error message requesting the user to send me an email with the details: exception type and message (if available).
Because of this I have already received many emails with IOException details.

But I was not treating Java Errors, only Exceptions. Because of this some users might see "Unhandled Error" messages shown by Java
Virtual Machine and will not know what to do. Next version will fix this and show a better message.
That is a good fix but does not solve the problem.

One thing I have learned is that reacting to Exceptions and Errors is not a good approach. The best thing to do is to antecipate
such situations and a situation we can antecipate is the OutOfMemoryError.

First, we need to know how much free memory is available. This can be done with
Runtime class.
Before trying to open a file I check if its size fits the current available memory with the following method:


boolean isThereEnoughMemoryToOpen (FileConnection file)
throws IOException
{
return Runtime.getRuntime().freeMemory() < file.fileSize();
}


If the method returns false (or throw an Exception) I do not open the file and show an error message to the user.

Related topics:

No comments: