Java : recursive constructor call and stackoverflow error

后端 未结 5 1941
醉话见心
醉话见心 2020-12-03 20:00

Please help to understand why does the following code

public class HeapQn1 {

    /**
     * @param args
     */
    public HeapQn1() {
        new HeapQn1(         


        
相关标签:
5条回答
  • 2020-12-03 20:24

    The constructor is a method, a.k.a. a function. Every time you call it a chunk of memory is allocated to the stack, to store the variables of the function.

    Your code creates calls to the constructor function indefenitely, allocating memory to the stack until the memory finishes.

    You are obtaining a StackOverflowError and not an OutOfMemoryError, because the quantity of memory dedicated to the stack is smaller than the quantity of memory dedicated to the heap.

    EDIT: I have done some test using your code. I've specified a heap memory space of 8M (-Xms8M -Xmx8M) and a stack memory space of 100M (-Xss100M). The computation result is always the error StackOverflowError.

    Then, this could mean that no memory is allocated to the heap in this case. As you stated in your question:

    The object is fully constructed/created when the constructor returns.

    0 讨论(0)
  • 2020-12-03 20:25

    As per the java all the reference variables are stored in the stack memory space and stack memory space is smaller than heap space that's what we get stackOverFlowException.

    0 讨论(0)
  • 2020-12-03 20:27

    Basically what you said is correct, the stack space runs out before the heap space does.

    0 讨论(0)
  • 2020-12-03 20:37

    Whenever the constructor is called, its return address is pushed onto the stack. As the stack is finite and smaller than the heap memory, you are getting error like StackOverflowError rather than OutOfMemoryError.

    The constructor is a method and since the heap memory is much larger than the stack memory, the recursive constructor call resulted in StackOverflowError. Is this correct ?

    Yeah, your wild guess is completely correct. Cheers!

    0 讨论(0)
  • 2020-12-03 20:40

    You are right: the stack is much smaller than the heap, and no object will be fully created.

    0 讨论(0)
提交回复
热议问题