What causes out of memory exceptions?
The dreaded OutOfMemoryException is something that no Java programmer ever wishes to see. Yet it can happen, particularly if your application involves a large amount of data processing, or is long lived - such as a server that responds to requests and is expected to run indefinitely.
There are several reasons that out of memory exceptions can be thrown. Either the virtual machine your Java program is running on may have a limit to the amount of memory it will give access to, the system on which your program is running may have run out of physical and virtual memory, or your application may just be consuming too much memory. In the first case, you may be able to modify the maximum heap size of the virtual machine, in the second or third you'll need to redesign your application.
Designing applications for minimal memory consumption isn't an easy task, and isn't specific only to Java programming. There are many techniques available, such as buffering data to disk that isn't needed at the moment, to using more efficient algorithms or subdividing tasks into smaller pieces. This is more of a design problem that a Java one - however there are some steps you can take to avoid your program crashing when it runs out of memory.
For a start, in your main method (or those you identify as likely to cause problems), catch OutOfMemoryExceptions. This way your application can terminate gracefully. Also, be sure to clear any data that you know you'll no longer require. The automatic garbage collector looks for objects that contain no references, so be sure to set your objects to null when you're finished. Finally, you can always examine the amount of free memory by calling the freeMemory() method of the system Runtime object. Here's how :
Runtime runtime = Runtime.getRuntime(); System.out.println ("Free memory : " - + runtime.freeMemory() );
If you realize that you're going to be performing large amounts of data processing (and consuming large amounts of memory), it might be a good idea to check before beginning. Here's to no more OutOfMemoryExceptions!