OutOfMemoryError in java

OutOfMemoryError is a subclass of java.lang.VirtualMachineError in java. It is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space and also, the garbage collector cannot free some space.

OutOfMemoryError will looks like

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Types of OutOfMemoryError

  • java.lang.OutOfMemoryError: Java heap space
  • java.lang.OutOfMemoryError: PermGen space

Reason of OutOfMemoryError (Java heap space)

  • OutOfMemoryError can occur because of Bad programming or Poor programming. For example: infinite loop or not clearing memory by closing resources etc.
  • OutOfMemoryError can occur because of Low Memory. Application is running on less memory than required.

OutOfMemoryError: Bad programming

import java.util.*; 
 
public class Main { 
public static void main(String args[]) throws Exception 
    { 
        List<Integer> randomList = new ArrayList<>();
        Random random = new Random(); 
        while (true) { 
            randomList.add(random.nextInt()); 
        } 
    } 
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at java.util.Arrays.copyOf(Arrays.java:3210)
	at java.util.Arrays.copyOf(Arrays.java:3181)
	at java.util.ArrayList.grow(ArrayList.java:261)
	at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
	at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
	at java.util.ArrayList.add(ArrayList.java:458)
	at Main.main(Main.java:9)

OutOfMemoryError: Low Memory

import java.util.*; 
 
public class Main { 
	static List<String> list = new ArrayList<String>(); 
 
public static void main(String args[]) throws Exception 
	{ 
	    System.out.println("OutOfMemoryError low memory test.");
		Integer[] array = new Integer[10000 * 10000]; 
	} 
}

Output

OutOfMemoryError low memory test.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at Main.main(Main.java:9)

Solutions of java.lang.OutOfMemoryError: Java heap space

  • Increase the maximum heap size: Use -Xmx and -Xms parameters to increase the size. e.g. if you want to increase the heap size for your java application. Use :
    export JVM_ARGS="-Xms1024m -Xmx1024m"

    Note: Try to use -Xmx and -Xms size in the ratio of either 1:1 or 1:1.5.

  • Analyze application memory leak: If you are still getting the OutOfMemoryError, after increasing the heap size then you can look into the memory leak issue. There are several tools available like Eclipse Memory Analyzer by which you can analyze the application heap dump and find the areas of memory leaks.

Java interview questions on Exception Handling

Content Protection by DMCA.com
Please Share