JavaBeat Certifications Certifications Kits Articles Interview Questions OCAJP 7 OCPJP 5 OCPJP 6 OCEJWCD 6 SCBCD 5.0 SCEA SCJA

What causes out of memory exceptions?

Topic :
Feedback Request New QnA Print Email

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!

Topic :
Feedback Request New QnA Print Email

All api java java 6.0 java 7.0 jdbc jsp servlet ejb jndi jms ejb 3.0 j2ee jee 5.0 jee 6.0 jsf struts spring Hibernate ajax JBoss Seam netbeans eclipse ant xml maven dojo junit javafx j2me log4j ESB JBoss Apache Quartz scjp mysql oracle gwt openjpa jmx yui google-guice android JBoss scwcd 5.0 scjp 1.5 scjp 1.6 scja scbcd 5.0

javabeat | advertise | about us | contact | useful resources
Copyright (2004 - 2013), JavaBeat