How do you deal with StackOverflowError in java ?
Problem statement: what is StackOverflowError and how do you deal with this ?
- Constructor of StackOverflowError class:
- StackOverflowError():creates an object of StackOverflowError class, with no details message.
- StackOverflowError(String s):creates an object of StackOverflowError class, with the specified detail message.
- Hierarchies of StackOverflowError class:
- StackOverflowError extends VirtualMachineError: it indicates JVM is broken
- VirtualMachineError extends Error: it indicates serious problem that an application should not catch.
- 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 ?
- when recursive function does not have the correct termination condition, then it ends up calling itself forever and leads to StackOverflowError.
- If you are calling library function that indirectly cause function to be called.
- How do you deal with StackOverflowError?
- Inspect the stack trace and detect the repeating pattern of line numbers.
- these line numbers indicates code being recursively called.
- once you detect these lines, inspect your code and understand why recursion never terminates.
- if code is terminating the recursion correctly, then increase the thread stack's size, in order to allow large number of invocations.
- default thread stack size is equal to 1MB.
- thread stack size can be increase using -Xss flag
- -Xss flag can be specified either via project's configuration, or via command line.
- value can be set like -Xss2048k or -Xss2M don't use = operator like -Xss=2048k
- public class StackOverFlowErrorExe {
- public static void recursiveCall(int num) {
- System.out.println("Number: " + num);
- if (num == 0) {
- return;
- }else {
- recursiveCall(++num);
- }
- }
- public static void main(String[] args) {
- StackOverFlowErrorExe.recursiveCall(1);
- }
- }
Output:
- How to configure -Xss flag in eclipse:
Comments
Post a Comment