w4 MemoryAllocation
w4 MemoryAllocation
Memory allocation in Java specifies the mechanism where the computer programs and
services are assigned dedicated virtual memory spaces. The Java Virtual Machine splits the
memory into Stack and Heap Memory.
Stack Memory
In Java, stack memory is used for static memory allocation and thread execution.
Methods, local variables, and reference variables are all stored in the Stack portion of
memory.
Since they are interpreted in a Last-In-First-Out way, the values in this memory are
temporary and restricted to particular methods. When a new method is created, a new
block is generated on top of the stack that includes values specific to that method, such as
primitive variables and object references.
When a method completes its execution, the resulting stack frame is cleared, the flow
returns to the calling method, and space for the next method becomes available.
Heap Memory
Any time an object is created and allocated in Java Heap Space, it is used. In heap memory,
new objects are often formed, and references to these objects are stored in stack memory.
Garbage Collection, a discrete function, keeps flushing the memory used by previous objects
that have no reference. A Heap Space object can have unrestricted access throughout the
program.
These objects are accessible from anywhere in the program and have global access.
Example:
class Test {
void show() {
System.out.println("Inside Test::show()");
}
}
Output:
Inside Test::show()
NOTE: Here 't' is a reference variable that refers to the test object that is in the heap
memory.
Garbage Collection in Java
Example:
public class Test
{
public static void main(String[] args) throws ExceptionInterrupted
{
Test t1 = new Test();
Test t2 = new Test();
@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}
Output:
Garbage collector called
Object garbage collected : Test@6fe026ef
Garbage collector called
Object garbage collected : Test@6127c563