Best way to get the remaining memory stack in Java?

What is the best way, during a recursive call, to either get or calculate the remaining remaining memory stack in Java?

(I'm trying to segment a deep recursive call to use as many stacks as possible (for the sake of speed performance), but without.

I already made a "bunch" version that carried the overhead of speed, so I am doing this optimization.)

+4
source share
5 answers

It is not possible to do this in a portable way.

Not only does this depend on the OS, in practice, the maximum stack size can be limited by several restrictions ( ulimit -c , the amount of available virtual memory, -Xss and -XX:ThreadStackSize , etc.). This makes it difficult to understand which restriction will be affected first, even if you can reliably measure how much stack space has been used so far.

+1
source

Why do you need this? Just curiosity? What are the units - bytes or the number of recursive calls?

You can always make an infinite recursive call, catch a StackOverflowError and count stack frames

+1
source

Hmmm. If you are worried, you can always keep a depth counter as part of your recursion.

+1
source

I would write a method less recursive. Often there are ways to make fewer (or none at all) recursive calls.

If you summarize the list recursively, adding the first value to the sum of the others, this will cause calls to a depth of N. However, if you cut the list in half and sum the values. (return value, if only one in the list), recursive depth - log2 (N).

+1
source

I am surprised that the iterative approach is less efficient. Typically, the recursive approach will be slower due to the overhead of method calls. If your algorithm can be implemented as tail-recursive, it will almost certainly be faster as an iterative implementation. Can you tell us more about what you are actually trying to do? Perhaps the performance difference is more algorithmic than just switching iterations for recursion. Here is an example from some CS lecture notes that refer to a recursive approach to calculating Fibonacci numbers, which is O (2 ^ n), while the iterative approach To). I believe (although I have not tried it) you can write a recursive Fibonacci number generator, which is O (n).

Edit:

Last thought. IMHO it would be much better to use a slower problem-free approach than introduce all the complexity in trying to determine that you are going to overflow the stack and have some kind of backup mechanism to avoid it.

+1
source

Source: https://habr.com/ru/post/1386322/


All Articles