2

I'm trying to check the stack safety of some very complex code, and would like a way to check the current depth of the call stack and get the result as an integer. I can kind of see how I'd stitch something together, but it involves imports and creating an exception... is there an easier or more elegant way?

For context, I have some very sophisticated, FP-heavy code that I suspect is not stack safe for arbitrary input. I have a lot of general ideas on how to check that, but I don't know that there isn't some black magic in play, so I'd like to check the actual stack depth.

EDIT: Someone suggested this as a duplicate, but:

  • When I try to use that method, it gives me inconsistent results - sometimes I get what looks like reasonable stack depth, others I get "10" for everything, including a test I wrote to intentionally stack overflow. I'm hoping there's an alternate method available.
  • Even if it is the best available, the question refers to Java, and it might be easier for future people investigating the Scala situation to find that it is in fact the same without having to ask.
Edward Peters
  • 3,623
  • 2
  • 16
  • 39
  • 2
    https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Thread.html#getStackTrace() – Luis Miguel Mejía Suárez Jan 17 '23 at 22:39
  • Would you have the possibility of applying the `@tailrec` annotation to the code you suspect is not stack safe and see what the compiler thinks about it? https://www.scala-lang.org/api/current/scala/annotation/tailrec.html You can still have stack safe code which is not tail recursive, but I'm wondering whether this applies to your case or not. – stefanobaghino Jan 18 '23 at 12:33
  • @stefanobaghino I cannot imagine it would be tail recursive, given that it is making multiple recursive calls in a loop, then returning a different call. – Edward Peters Jan 18 '23 at 14:46
  • @LuisMiguelMejíaSuárez Huh, for some reason I had to open that in a different browser for it to display properly. Anyway, I'm trying that technique but it's giving weird results - sometimes it will always and only show a depth of 10, other times its in the 50s and increasing. (I'm pretty sure the actual behavior is consistent, but something funny is happening with the generated trace - it shows 10 even when I write something that definitely overflows the stack.) – Edward Peters Jan 18 '23 at 15:01
  • Can you add the output to the question as well as the code that generates it? – Tim Moore Jan 20 '23 at 01:40

0 Answers0