Showing posts with label OutOfMemoryError. Show all posts
Showing posts with label OutOfMemoryError. Show all posts

Tuesday, 25 February 2014

Difference between Error Vs Exception

1. Error are abnormal situations where program can't handle those, where as Exception is also a abnormal situation, but program handle the exception.

2. Error, RuntimeExceptions and its subclasses comes under uncheckedexceptions category, where as Exception and its sub classes comes under checked exceptions category.

3. Almost in all the cases, program is not recoverable from an error,
Ex: OutOfMemoryError, StackOverflowError. But you can catch the exception and recover from that.

4. Both error and RuntimeException comes under unchecked exceptions category, program can handle RuntimeException, where as it can't handle error


Exception Hierarchy                                                 Throwable class                                                 Home

exception hierarchy

Exception Hierarchy


Throwable is the super class for all the exceptions in Java. Error, Exception are the two direct known subclasses for the Throwable class.

Error is a subclass of the Throwable, where a program can't handle. Exception is a sub class of the class Throwable, where program can handle.

Examples of Errors are

VirtualMachineError, InternalError, OutOfMemoryError, StackOverflowError.

Suppose if your program using the maximum heap and unable to allocate memory for new object, then OutOfMemoryError occurs. Definitely, your program can't handle the error.


java7 support for suppressed exceptions                                                 error vs exception                                                 Home

Thursday, 13 February 2014

How to increase Heap size in java

Run the following program
 
class HeapEx{
 public static void main(String args[]){
  HeapEx obj[] = new HeapEx[100000000];
  
  for(int i=0; i<100000000; i++)
   obj[i] = new HeapEx();
   
  System.out.println("I am done");
 }
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at HeapEx.main(HeapEx.java:8)

OutOfMemoryError thrown when the Java Virtual Machine unable to allocate memory for an object, and no more memory could be made available by the garbage collector.

To Increase the heap size, java provides an option -Xmx
Option
Description
-Xms
Set initial and minimum heap size
-Xmx
Set maximum heap size

The JVM heap can vary its Current heap size between two preconfigured memory boundaries – the initial heap size (defined by the –Xms option) and the maximum heap size (defined by the –Xmx option)

Syntax
-Xms<size>[g|G|m|M|k|K]
-Xmx<size>[g|G|m|M|k|K]

To make the above program run, I increased the size of heap memory to 5000mb like below

java -Xmx5000M HeapEx

Output
I am done

Heap memory                                                 Object Creation and destruction                                                 Home