Sunday, July 24, 2011

Is It Possible To Catch OutOfMemoryError

Many of the Java techies wanted to know "Is it possible to catch the OutOfMemoryError". YES, we can catch this Error, because it is extending from Throwable class. You can release some memory when this exception occurs.
If there are some non daemon threads are running those do not do any memory related operation then the application will continue running, it will not corrupt otherwise it will.
See the below example in which we are releasing memory :

package exception;

import java.util.ArrayList;
import java.util.List;

public class OutOfMemoryErrorTest {

 static List lst = new ArrayList();
 public static void main(String args[])
 {
  try
  {
   Thread thr = new Thread( new Runnable() {
    
    @Override
    public void run() {
     while(true){
      System.out.println("working...");
      try {
       Thread.sleep(5000);
       System.out.println("Adding..");
       lst.add("dfdf");
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
     
    }
   });
   
   thr.start();
   while(true) {
    lst.add("dfdf");
   }
  }catch(OutOfMemoryError e ) {
   e.printStackTrace();
   System.out.println("Error Catched.....");
   lst.clear();
   System.out.println("Memory released...");
  }
  
 }
}



Output :

working...
java.lang.OutOfMemoryError: Java heap space
Error Catched.....
 at java.util.Arrays.copyOf(Arrays.java:2760)
 at java.util.Arrays.copyOf(Arrays.java:2734)
 at java.util.ArrayList.ensureCapacity(ArrayList.java:167)
 at java.util.ArrayList.add(ArrayList.java:351)
 at exception.OutOfMemoryErrorTest.main(OutOfMemoryErrorTest.java:33)
Memory released...
Adding..
working...
Adding..
working...



As we can see in the output, we can catch the OutOfMemoryError and we released the memory and application continue to work as normal without being corrupted.

Conclusion

  • If you are getting OutOfMemoryError in your application then it might be possible that you are not handling the objects properly means objects are not getting garbage collected, because you are keep on storing those objects in memory.
  • When java application sees that the memory is being short then JVM first triggers the GC and see if that releases the memory. If GC is unable to clean the objects as those objects are strongly referenced then this leads to the OutOfMemoryError.
  • If your application needs more memory to run stably then you need to give your application more memory by specifying –Xmx in VM arguments.