If the recursive algorithm is ever only executed by one thread, you
can increment a static variable in the enclosing class. Otherwise
you'd have to set up counts for each thread using ThreadLocal.
In order to avoid threading issues and the need to reset the state
afterwards, I'd rather suggest using an accumulator (a common idiom
with recursion):
1. if the method doesn't already have something to return, keep track
of and return the depth with a primitive:
int recursiveMethod(int foo, int depth) {
if (isBaseCase(foo)) {
return depth;
}
else {
return recursiveMethod(int foo, depth+1);
}
}
2. if the method already uses the return value for something useful,
pass an object instead:
MyData recursiveMethod(int foo, Depth d) {
if (isBaseCase(foo)) {
return baseValue;
}
else {
return recursiveMethod(foo, d.increment());
}
}
You won't have to change any of the code that calls your function if
you use a wrapper:
MyData myFunction(int foo) {
Depth d = new Depth(0);
MyData r = myFunctionHelper(foo, d);
System.out.println("Depth was " + d.getDepth());
return r;
}
/gordon