Manoj Majumdar
Manoj Majumdar

Reputation: 525

Display available stack memory in Java

I am trying to display the consumed stack space during a recursive program execution, like inorder traversal of a tree. Is there a way to print the available stack space in Java, I know that available heap memory could be displayed using Runtime.getRuntime().freeMemory().

Upvotes: 0

Views: 670

Answers (1)

Joachim Sauer
Joachim Sauer

Reputation: 308249

Java doesn't give you access to this kind of information, for various reasons:

  1. keeping track of that information might actually make some kinds of optimizations impossible
  2. giving an exact number at a certain point might slow down the execution (due to a potentially necessary de-optimization).
  3. the exact amount of available space left might vary over time (for example if stack space were dynamically allocated from a shared space and not fixed).
  4. Any value you might get is very likely to only be of limited value (as you can't know for sure how many bytes a given method invocation needs in various scenarios).

The closest you can get is to get a current stack trace (for example using Thread.getStackTrace()) and check the returned arrays size to know how many stack frames are in use (i.e. how deep the stack already is).

But even that operation is likely to be somewhat costly.

Upvotes: 1

Related Questions