Wednesday, May 9, 2018

How do you deal with StackOverflowError in java?

Problem statement: what is StackOverflowError and how do you deal with this ?
  • Constructor of StackOverflowError class:
  1. StackOverflowError():creates/constructs an object of StackOverflowError class, with no details message.
  2. StackOverflowError(String s):creates/constructs an object of StackOverflowError class, with the specified detail message.
  • Hierarchies of StackOverflowError class: 
  1. StackOverflowError extends VirtualMachineError: it indicates JVM is broken
  2. VirtualMachineError extends Error: it indicates serious problem that an application should not try to catch.
  3. Error extends Throwable and furthermore Throwable extends Object.
  • What is StackOverflowError: Stack overflow means exactly - a stack overflows. Usually there's a one stack in the program that contains local-scope variables and addresses where to return when execution of a programs ends. That stack tends to be a fixed memory range somewhere in the memory, therefore it's limited how much it can contain values.
  • If the stack is empty you can't pop, if you do you'll get stack underflow error.
  • If the stack is full you can't push, if you do you'll get stack overflow error.
  • So stack overflow appears where you allocate too much into the stack.
  • what is the cause of StackOverflowError ?
  1. when recursive function does not have the correct termination condition, then it ends up calling itself forever and leads to StackOverflowError.
  2. If you are calling library function that indirectly cause function to be called.
  • How do you deal with StackOverflowError?
  1. Inspect the stack trace and detect the repeating pattern of line numbers. 
  2. these line numbers indicates code being recursively called.
  3. once you detect these lines, inspect your code and understand why recursion never terminates.
  4. if code is terminating the recursion correctly, then increase the thread stack's size, in order to allow large number of invocations.
  5. default thread stack size is equal to 1MB.
  6. thread stack size can be increase using -Xss flag
  7. -Xss flag can be specified either via project's configuration, or via command line.
  8. value can be set like -Xss2048k or -Xss2M don't use = operator like -Xss=2048k
  1. public class StackOverFlowErrorExe {
  2. public static void recursiveCall(int num) {

  3. System.out.println("Number: " + num);

  4. if (num == 0) {
  5. return;
  6. }else {
  7. recursiveCall(++num);
  8. }
  9. }

  10. public static void main(String[] args) {
  11. StackOverFlowErrorExe.recursiveCall(1);
  12. }
  13. }
Output: Exception in thread "main" java.lang.StackOverflowError.

  • How to configure -Xss flag in eclipse:


No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...