tags:

views:

216

answers:

3

i know that i can get stacktrace by using Thread.getAllStackTraces()(it returns Map, but clear does not work). When I run recursion method i can get exception because of stacktrace being too big, is there any way to clear it?

+4  A: 

It's not the stack trace that is causing your problem, it's the stack itself. Every time you call a method, information gets put on the stack that allows you to return to the calling method. If you recurse enough, eventually you fill all the space on the stack (which is bound by a maximum size) and your program stops. The stack trace simply shows you your history of calls. You probably have an infinite recursion going on and need to find a way to stop it before your program fails. Either there is an error in your algorithm or you need to find a way to solve it differently within the bounds of the memory available to you.

tvanfosson
+1  A: 

If you are hitting a stack overflow due to recursion going out of control, you are out of luck. The stack's contents is needed to return from function calls, there is no way to sensibly "clean it". The problem is not the Map returned by getAllStackTraces(), but rather the actual contents of the stack.

You need to restructure your code so that it doesn't recurse to such a deep level.

Alternatively, you could investigate if it is possible to increase the size of the stack, but requiring a non-standard stack size is generally a sign of a problematic implementation.

unwind
A: 

First check that your program doesn't have a bug in its code causing an infinite recursion leading to the stack overflow.

If it is not the case, you may try to allocate more stack space to your program. Under Linux you can do it with the ulimit bash command like:

ulimit -s 8000

or even

ulimit -s unlimited

If you really need to unwind the stack you can use setjmp/longjump in C or use exceptions or continuations like:

struct ClearStack {} ;

void myLongComputationWhichCausesStackOverflow() {
  // do something
  if (needsToClearTheStack)
    throw ClearStack() ;
  // do something else
}

int main(int ac, char *av[]) {
  try {
    mylongcomputation() ;
    // continuation of program
    // no stack clearing occurred
  }
  catch(const ClearStack & cs) {
    // the stack was cleared and do something appropriately
  }
}

It does what you want but it is not really a good programming style. Note that you need to come up with a way to know when to clear stack. This may be quite difficult as you cannot know how much stack space is left or if calling a function will overflow the stack !

Pierre
This is useful information, but does not apply to this question.
Steve g