• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StackOverflowError

 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the following method from jqplus6:


int factorial(int n)
{
if(n==1)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}



According to the answer given in the evaluation this method, if called with a very big integer, will throw StackOverflowError. I understand the concept that stands beyond that but I was wondering if we will always get the StackOverflowError?

I mean does the JVM has some fixed amount of memory reserved or it is dependant of the system? Can we theoretically, having lots of memory and operating system ready to give it to the JVM, finish to perform this method without StackOverflowError?
[ May 11, 2008: Message edited by: Ismael Upright ]
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ismael,

Have you tried testing this out on your own machine to see at what size Integer you get a StackOverflowError (note: it's and Error, not an Exception)?

You can use the -Xoss (Java stack size) and -Xss (native stack size) parameters to increase the JVM's stack size, but this has other implications. Usually, when you find your code generates a StackOverflowError, you will want to figure out how to reduce the depth of your recursion to eliminate the problem that way.

Of course, well before you get the StackOverflowError, the code as written will return an invalid answer.
 
Ismael Upright
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for my mistake, it's error, not exception...

I was thinking about the following situation: assume that we run this method for Integer.MAX_VALUE. Is there ANY chance that this code will not throw StackOverflowError on ANY theoretical machine?


And my second question: does the JVM has some fixed amount of memory reserved to run independenty of the operating system?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1: It's a very theoretical question, and the answer most likely depends on the implementation of the JVM. Ofcourse someone could make a JVM that uses a really large stack that could execute this method for Integer.MAX_VALUE without going out of stack space.

2. It depends on the implementation of the JVM that you are using, but Sun's JVM running on PCs does not allocate more memory than it needs, and allocates more if needed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic