Saturday 2 September 2017

How to generate the StackOverflowError and OutOfMemoryError programmatically in Java

      Every Java Developer can face this type of error while developing application.  Mostly you will get the java.lang.OutOfMemoryError due to the system memory limitation rather than programming mistake. In this case,  you can increase the heap size of JVM by default it should be 256MB(Java 6).

      In this post, will discuss how to generate the OutOfMemoryError and StackOverflowError programmatically.  In OutOfMemoryError, again two types  PermGen space and heap space.
      If declared more String literals in application then it will throw PermGen Space error.  If you created so many Objects using new keyword and not garbage collected for unreferenced objects, it will throw heap space error because there is no sufficient memory to create the new objects.

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 primitive datatype, variables and method invocation and method calls.  If variables are removed, memory is freed for other variables at the end of the method execution. The JVM will throw java.lang.StackOverflowError if there is shortage of memory in the stack area.
       Below code is to generate the StackOverflowError programmatically,  by using the recursive 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