Table of contents
1.
Introduction
2.
What is Virtual Memory?
3.
Java Virtual Machine
4.
What is Stack Memory?
4.1.
Characteristics of Stack Memory
5.
What is Heap Memory?
5.1.
Characteristics of Heap Memory 
6.
Differences between Stack and Heap Memory
7.
Frequently Asked Questions
7.1.
What happens when the stack runs out of memory?
7.2.
Can objects stored on the heap be accessed by multiple threads?
7.3.
How does the JVM handle memory deallocation on the heap?
8.
Conclusion
Last Updated: Nov 8, 2024
Medium

Dynamic Memory Allocation in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Dynamic memory allocation is a mechanism by which programs can obtain memory at runtime. It is a crucial concept in Java-related programming. It allows programs to allocate and deallocate memory during runtime based on their needs rather than a fixed memory size. This flexibility is essential for optimizing memory usage and creating efficient programs. 

Dynamic Memory Allocation in Java

In this article, we will discuss the basics of dynamic memory allocation in Java, like the role of the Java Virtual Machine (JVM) and the differences between stack and heap memory. 

What is Virtual Memory?

Virtual memory is a memory management technique used by operating systems to provide an illusion of having more memory than is physically available. It allows programs to run that require more RAM than is installed on the computer. When a program needs memory, the operating system allocates virtual memory to it. This virtual memory is mapped to physical memory (RAM) or to a file on the hard disk called a page file or swap file. The operating system keeps track of which parts of virtual memory are currently in physical memory & which are on disk. When a program tries to access virtual memory that is not currently in physical memory, the operating system copies the required data from the disk to RAM, a process which is known as paging. This allows programs to use more memory than is physically present, although during this, accessing data from disk is slower than accessing it from RAM.

Java Virtual Machine

The Java Virtual Machine (JVM) is an integral part of the Java platform. It is an abstract computing machine that provides a runtime environment in which Java bytecode can be executed. When you compile a Java program, the compiler generates bytecode instead of machine code. This bytecode is platform-independent & can run on any device that has a JVM installed. The JVM acts as an intermediary between the bytecode & the underlying hardware, interpreting the bytecode & translating it into machine code, which is specific to the device's processor. This is the main reason why Java programs follow the "write once, run anywhere" principle. The JVM also manages memory allocation & deallocation for Java programs using a combination of stack & heap memory. It performs automatic memory management through a process called garbage collection, which frees developers from manually managing memory & helps prevent common memory-related errors like memory leaks & dangling pointers.

What is Stack Memory?

Stack memory is a special region of memory that is used for storing local variables, method parameters, & method invocation details. Whenever a new method is called, a new block of memory called a stack frame, is allocated on top of the stack. This stack frame contains the method's local variables, the parameters passed to the method, & a return address to the code that called the method. When the method finishes execution, its stack frame is popped off the stack, & the flow of control returns to the calling code. The stack size is determined at the start of the program & does not change during runtime. If too many method calls occur & the stack runs out of space, a stack overflow error occurs. Access to data stored in the stack is very fast because there's a marker called the stack pointer that consistently indicates the top of the stack. When a program needs to use local variables or parameters from a method, it simply checks how far these are from the marker. This direct method of checking makes accessing this data quick and efficient. However, because of its fixed size, the stack is more limited in storage capacity than heap memory.

Characteristics of Stack Memory

1. Fixed Size: The stack size is determined when a thread is created & cannot be changed during runtime. Each thread has its own stack.
 

2. Fast Access: Data in the stack can be accessed very quickly because the stack pointer always points to the top of the stack. Local variables and method parameters can be accessed quickly by offsetting from the stack pointer.

 

3. LIFO (Last-In-First-Out) Structure: The stack follows a LIFO structure, meaning that the last item added to the stack is the first one to be removed. This is why it's called a stack - it works like a stack of plates, where you can only add or remove plates from the top.
 

4. Automatic Allocation & Deallocation: The JVM handles memory allocation and deallocation in the stack automatically. When a method is called, its stack frame is automatically pushed onto the stack. When the method finishes, its stack frame is automatically popped off the stack.
 

5. Limited Storage Capacity: Because the stack's size is fixed, it has a limited storage capacity. If too many method calls occur and the stack runs out of space, a stack overflow error will occur.
 

6. Stores Local Variables & Method Parameters: The stack stores local variables, method parameters, & method invocation details. Each method call creates a new stack frame that holds these details.

What is Heap Memory?

Heap memory is a region of memory that is used for the dynamic allocation of objects and classes. Unlike stack memory, which is fixed in size & automatically managed by the JVM, heap memory is flexible in size & requires manual memory management. When you create an object using the "new" keyword in Java, that object is allocated memory on the heap. The heap size can change during runtime, growing or shrinking as needed to accommodate the creation & destruction of objects. When there is no more space left in the heap for object allocation, the JVM will attempt to reclaim unused memory through a process called garbage collection. Objects on the heap can be accessed globally, meaning they can be referenced from anywhere in the program if there is a valid reference to the object. However, accessing data on the heap is slower than accessing data on the stack because it involves navigating through a complex structure of memory addresses. Proper management of heap memory is crucial for program performance & avoiding memory leaks, which occur when objects are no longer needed but continue to consume memory because they have not been properly deallocated.

Characteristics of Heap Memory
 

1. Dynamic Size: The size of the heap can change during runtime, growing or shrinking as needed to accommodate the creation & destruction of objects.
 

2. Slower Access: Accessing data on the heap is slower than accessing data on the stack because it involves navigating through a complex structure of memory addresses.
 

3. Garbage Collection: The JVM automatically manages heap memory through a process called garbage collection. When an object is no longer referenced by any part of the program, it becomes eligible for garbage collection, & the memory it occupies can be reclaimed.
 

4. Global Access: Objects on the heap can be accessed globally, meaning they can be referenced from anywhere in the program if there is a valid reference to the object.
 

5. Manual Memory Management: While the JVM handles garbage collection, it's still the programmer's responsibility to manage heap memory by properly allocating & deallocating objects. Failing to do so can lead to memory leaks.
 

6. Stores Objects & Classes: The heap stores objects and class instances created using the "new" keyword. This includes both user-defined objects and objects created by the Java runtime, such as Strings and arrays.
 

7. Shared Across Threads: Unlike stack memory, which is specific to each thread, heap memory is shared across all threads in a Java application. This means that multiple threads can access & modify the same objects on the heap.

Differences between Stack and Heap Memory

Stack MemoryHeap Memory
Stack memory is a fixed-size region of memory used for storing local variables, method parameters, and method invocation details.Heap memory is a dynamic-size region of memory used for allocating objects and class instances.
The stack size is determined when a thread is created and cannot be changed during runtime.The heap size can grow or shrink during runtime as needed to accommodate object creation and destruction.
Accessing data in the stack is very fast because the stack pointer always points to the top of the stack.Accessing data on the heap is slower than accessing data on the stack because it involves navigating through a complex structure of memory addresses.
The stack follows a Last-In-First-Out (LIFO) structure, meaning that the last item added is the first one to be removed.The heap does not follow a specific structure, and objects can be allocated and deallocated in any order.
Memory allocation and deallocation in the stack is handled automatically by the JVM.Memory management on the heap is handled by the JVM through garbage collection, but it's the programmer's responsibility to properly allocate and deallocate objects.
The stack has a limited storage capacity, and if too many method calls occur, a stack overflow error will occur.The heap has a larger storage capacity than the stack, but if it runs out of space, the JVM will attempt to reclaim memory through garbage collection.
The stack stores local variables, method parameters, and method invocation details specific to each thread.The heap stores objects and class instances that can be accessed globally by any thread in the Java application.

Frequently Asked Questions

What happens when the stack runs out of memory?

When the stack runs out of memory due to too many method calls or deep recursion, a stack overflow error occurs, and the program will terminate abruptly.

Can objects stored on the heap be accessed by multiple threads?

Yes, objects stored on the heap can be accessed by multiple threads simultaneously, as the heap is shared across all threads in a Java application.

How does the JVM handle memory deallocation on the heap?

The JVM handles memory deallocation on the heap through a process called garbage collection, which automatically identifies and removes objects that are no longer referenced by the program.

Conclusion

In this article, we have discussed the basics of dynamic memory allocation in Java, which focuses on the differences between stack and heap memory. We learned that the stack is used for storing local variables and method invocation details, while the heap is used for allocating objects and class instances. The JVM manages memory differently for stack and heap, with the stack being automatically handled and the heap requiring garbage collection. 

You can also check out our other blogs on Code360.

Live masterclass