Download
Memory Mamagement in Java - Heap & Stack :
The instructions of a running program and related data are stored temporarily in the computer's memory. If you are a Java programmer, you do not need to worry about memory management because the JVM and GC (Garbage Collection) will do this job.
However, you should know how to organize the memory management of Java. This will help you understand the way an object is created. As shown in the figure above, the data of the program are located in two different areas in memory: stack and heap. Stack and heap references to different areas to store in the memory the elements of a program is running.
Store in the Stack
The following elements will be stored in Stack:• Local variables: These are variables value (or primitive) type is defined within a method or as an argument of the method.
• Local reference variables : The variables reference to an object and is defined inside a method or as an argument to the method. Please note that an object that a local variable references to be stored on the heap that is not on the stack.
• Invoking method: When you call a method, the method is pushed on the stack (ie, at the top of the stack).
Note: Local reference variables are declared within a method, and scope of a local reference variable since the declaration to the end of the method execution. When the implementation method is complete (finish), the local reference variables of the method will be freed. But the objects that local references variables reference to can still alive and still stored on the heap.
Store in the Heap
The following elements will be stored in the Heap:• Instance variables: These are variables value (or primitive) type are defined within a class but declared outside of all the methods in that class.
• Instance reference variables: Those are the variables reference to an object and are defined within a class, but is declared outside all the methods of that class.
• Objects: Represent for the entities in the real world problems that Java programs trying to solve. All objects are always stored on the memory heap. The object when no longer used (or reference) to be GC invoked to free up memory.
0 comments :
Post a Comment