Wednesday, April 24, 2019

StackOverflowError in java

Q- What is a Stack Overflow Error in java? or  What is StackOverflowError in Java?
Why and when StackOverflowError occur in java?

StackOverflowError is run time exception extends java.lang.Error in java.
StackOverflowError is occur due to insufficient or low memory in stack during method execution.
because in java, Stack is used to execute methods of a class.

When a method of class is invoked by a Java application, a stack frame is allocated to execute a method in stack.
If method execution required the more space then the space allocated to stack by JVM.
This may occur due to not proper programming into method like non controllable recursion call etc.
Or
If there is no space for a "new stack frame" then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

The most of case, it can possibly exhaust a Java application's stack is recursion.

StackOverflowError Examplpe in java
package com.shubh.java.example;

public class StackOverflowExample {
 
 // recursivePrint to print recursively
 public static void recursivePrint(int num) {
  System.out.println("Number: " + num);
  if (num == 0)
   return;
  else
   recursivePrint(++num);
 }

 public static void main(String[] args) {
  try {
   StackOverflowExample.recursivePrint(1);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}

 Output: 
Exception in thread "main" java.lang.StackOverflowError
        at java.io.PrintStream.write(PrintStream.java:480)
        at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
        at sun.nio.cs.StreamEncoder.implFlushBuffer(StreamEncoder.java:291)
        at sun.nio.cs.StreamEncoder.flushBuffer(StreamEncoder.java:104)
        at java.io.OutputStreamWriter.flushBuffer(OutputStreamWriter.java:185)
        at java.io.PrintStream.write(PrintStream.java:527)
        at java.io.PrintStream.print(PrintStream.java:669)
        at java.io.PrintStream.println(PrintStream.java:806)
        at StackOverflowExample.recursivePrint(StackOverflowErrorExample.java:11)

Q- How to avoid StackOverflowError  in java? or How to avoid java.lang.StackOverflowError?

1. Code should be written properly.
2. Increase memory :
To increase the memory of JVM allocation and thread stack size for Tomcat from the command line Open the catalina.bat file (TomcatInstallDirectory/bin /catalina.bat). Add the following below line:

set JAVA_OPTS=%JAVA_OPTS% -Xms1024m  -Xmx1024m

where:
  • Xms is the initial (start) memory pool.
  • Xmx is the maximum memory pool.
  • Xss is the thread stack size.

No comments:

Post a Comment