How to implement stack trace on failure?

I recently had an interview and was asked to design / implement a stacktrace function. This is what I came up with.

  • Maintain a stack containing all method calls from the main entry point into the program.
  • If there is an error at run time, stop the program and print the entire stack by clicking on each item.

Then I was asked two questions:

  • How / where will this stack be initialized?
  • How would you determine how much data a stack should store without using OOM? Why does the JVM never start OOM because of the stack?

For the first question I said, the stack must be static and must be initialized at the beginning of the program. But I was not sure about the second question. I tried to read how the JVM does this, but it was a bit complicated. I tried a google search for basic implementations but could not find. I would really appreciate it if someone just pointed me in the right direction as to what exactly I should look for in order to answer this.

+5
source share
3 answers

A bit of an open question, here is my trick:

  • The stack should not be static - during the life cycle of the program, you can add and remove one stack per thread, not per program, as well as threads. Thus, the stacks should be allocated dynamically.
  • Java stack may overflow. What may differ from OOM, but not so. As for what to store on the stack, I would go with a custom user, since there are very different requirements when working in development or production mode. You can also discuss possible stack management improvements, such as tail call optimization . This will prevent stack overflows, but will affect how the code is written.

Anyway, my 2 ยข.

0
source

I will not store the stack trace information anywhere, as it is already stored in the stack frame for each thread. When a stack trace is required (for example, an exception is thrown), I would build it from the stack frame.

The problem is that I'm not sure if there is all the information needed for this in the stack frame.

0
source

Call Thread.currentThread (). getStackTrace () to return a StackElement [] that can be printed in your log.

0
source

All Articles