0

I've been trying to resolve a stack overflow exception in my java code which occurs due to a number of recursion that I'm doing. I got to know that increasing the stack size in the Eclipse IDE kinda resolves this. I wanted to know that if this exception, as it occurs with the JVM, occurs as we create an executable and run. Doesn't the OS take care of the memory required for that executable?

Sujju
  • 97
  • 8
  • No. You have to provide the Max allowed memory for the operation. Take a simple example, if your code is running infinitely and JVM is allocating all the available memory to it, all of it. what will happen?? – Aditya Peshave Mar 27 '14 at 05:26
  • Thank you for the quick response. 1. My code doesn't run infinitely. It just does more recursions depending on the inputs. I've increased the stack size for JVM and it runs fine. 2. I'm concerned about what happens if an exe is created with the same code and run. – Sujju Mar 27 '14 at 05:28
  • Well, I am not talking about your code. I was simply giving you an example. ;) – Aditya Peshave Mar 27 '14 at 05:30
  • Where is your code? The fact that you're generating stack overflow exceptions at all is an indication of a programming error or bad design. Increasing memory and stack size won't solve that issue in the long run, it will probably come back to cause you big problems anyway. –  Mar 27 '14 at 05:53

1 Answers1

0

There are two different types (conceptually) of memory used while running application.

The heap is where object instances are being created and stored. This is the main part of the memory, which is also being garbage collected by the JVM, and the OS is indeed responsible for allocating this memory to your application. Having said that, the JVM is always started with a certain configuration of the maximum amount of memory it might get from the OS (this is configurable).

The second type of memory is called stack, and it is used internally by the JVM to support method calls. When you call a method the parameters you pass to the method are being placed on the stack, and are referenced whenever you reference a method parameter. Another usage of the stack is for method local variables (i.e. variables that you defined form within a method).

Stack overflow occurs when you run out of stack (how surprising). Due to the nature of its usage, stack is much more limited than heap, and should not be abused. If you have recursive methods that traverse entire trees/hierarchies, and you get to a point where you get stack overflow exceptions with larger inputs, it's definitely a sign that you should convert your recursions to iterations (see: Design patterns for converting recursive algorithms to iterative ones)

Community
  • 1
  • 1
ethanfar
  • 3,733
  • 24
  • 43