Why does Java uses heap for memory allocation?

前端 未结 7 530
别那么骄傲
别那么骄傲 2020-12-09 11:15

I just read this statement in a java book saying Objects in java reside on a heap. Is a heap used because it is the best way to store data and retrieve data fast ?

7条回答
  •  庸人自扰
    2020-12-09 11:37

    Java can store objects on the stack, if it does escape analysis that determines that no references to the object are retained by non local objects when the method returns. It does not allow you to declare that an object is stored on the stack.

    If Java did allow objects to be explicitly on the stack, what would happen when the method returned? What would happen to any references to the local object, held by any non local objects?

    • The Java designers could have decided that some references could be invalid, leading to undefined behaviour if dereferenced. Just like a pointer in C/C++. The Java designers seem to have gone to great lengths to avoid undefined behaviour.

    • The Java designers could have specified that all references to the local object became null. Finding all those references would be difficult. And it would result in difficult to find bugs caused by references that were assumed to be not null suddenly became null. Immutable objects containing object references would be impossible. And the notification mechanism that set references to null would have to work across threads. The cost of all this would be much higher than the advantage of local storage.

    • One of language designers, James Gosling, has a Lisp background, and that influence is visible in the idea that object disposal is just left to the garbage collector, with the compiler or run time environment optimising object disposal (escape analysis) if possible.

提交回复
热议问题