Memory allocation and deallocation are not very simple and heap memory uses complex memory management techniques.It is also a lot slower than the Stack memory.The heap memory is not as safe as the stack memory because all the threads can access the objects and we must synchronize them.Unlike the Stack memory, which uses the stack data structure, the heap data structure is in no way linked to the heap memory.Heap memory is also globally accessible and any thread can access the memory. All dynamic memory allocation takes place in the heap. As discussed above, the references to these objects are stored in the Stack memory. The heap memory is the place where all class instances or objects are allocated memory.The final stack memory is shown in the image below. All these methods blocks in the stack will have the required data available to them. ![]() Inside the print() method, we are calling the printChar() method, and a block for this method is allocated on the stack. Then we are calling the print() method, which will again be added to the top of the stack. This main() method will be pushed on the top of the stack. In the code below, we are creating primitive integer data and char data in the main() method. Let's see an example to understand how memory is allocated in the stack. In the following code, we recursively call the overflowError() method inside its definition and this leads to StackOverflowError. If we repeatedly call a method, then these method calls will accumulate in the Stack, and eventually, we will get this error. We can write a simple program to simulate this error. We may encounter the StackOverflowError if we run out of the Stack memory.And when the method finishes execution or returns, then the block and all the corresponding data are removed and the space becomes available for new method calls. Whenever a method is called, then a new block for this method is added at the top of the Stack. Allocation and deallocation of memory are done automatically.It is thread-safe and does not require synchronization as each thread gets its own Stack. ![]() It is also safer than heap memory because the data can only be accessed by the running thread.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |