java.lang.OutOfMemoryError occurs because the JVM runs out of available memory, although memory leaks or inefficient code can also be contributing factors. If the issue is caused by insufficient heap memory, you can increase the JVM heap size using the -Xms and -Xmx options. (For example, the default maximum heap size in older Java versions such as Java 6 was relatively small.)In this post, we will learn how to generate OutOfMemoryError and StackOverflowError programmatically.
OutOfMemoryError can occur for different reasons. In older Java versions (Java 7 and earlier), two common types were:
PermGen Space (
java.lang.OutOfMemoryError: PermGen space)Java Heap Space (
java.lang.OutOfMemoryError: Java heap space)
A PermGen Space error could occur if the Permanent Generation became full, often due to excessive class loading or metadata retention. (Note: PermGen was removed in Java 8 and replaced with Metaspace.)
A Java Heap Space error occurs when the application creates more objects than the available heap memory can accommodate, and the garbage collector is unable to reclaim enough memory because many objects are still reachable.
java.lang.OutOfMemoryError : java heap space examples(Source code)
package com.pr; public class heapSpaceError { public void method() { int value = 10; for (int i = 0; i<100; i++) { int count = 5; int[] a = new int[value]; value = value * 5; System.out.println(a); } } public static void main(String[] args) { heapSpaceError error = new heapSpaceError(); error.method(); } }
Output : --
[I@eb42cbf
[I@56e5b723
[I@35a8767
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.pr.heapSpaceError.method(heapSpaceError.java:9)
at com.pr.heapSpaceError.main(heapSpaceError.java:16)
java.lang.StackOverflowError examples(Source code)
The JVM stack is used to store local variables, primitive data types, object references, and method call information for each thread. When a method completes its execution, its stack frame is removed, and the memory occupied by the local variables is automatically released.
The JVM throws a java.lang.StackOverflowError when the stack memory is exhausted. This typically happens due to excessive or infinite recursive method calls, causing the stack to overflow.
The following example demonstrates how to generate a StackOverflowError programmatically using recursive method calls.
package com.pr; public class StackOverflowErrorEx { public int m(int i) { return m(i++); } public static void main(String[] args) { StackOverflowErrorEx ex = new StackOverflowErrorEx(); ex.m(1); } }
Output :--
Exception in thread "main" java.lang.StackOverflowError
at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6)
at com.pr.StackOverflowErrorEx.m(StackOverflowErrorEx.java:6)
Related Post:-
What is PermGen in Java? How to solve the Java.Lang.OutOfMemoryError: PermGen Space
No comments:
Post a Comment