The Wayback Machine - https://web.archive.org/web/20241004192858/https://www.geeksforgeeks.org/java-memory-management/
Open In App

Java Memory Management

Last Updated : 14 Dec, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article will focus on Java memory management, how the heap works, reference types, garbage collection, and also related concepts.

Why Learn Java Memory Management?
We all know that Java itself manages the memory and needs no explicit intervention of the programmer. Garbage collector itself ensures that the unused space gets cleaned and memory can be freed when not needed. So what’s the role of programmer and why a programmer needs to learn about the Java Memory Management ? Being a programmer, you don’t need to bother with problems like destroying objects, all credits to the garbage collector. However the automatic garbage collection doesn’t guarantee everything. If we don’t know how the memory management works, often we will end up amidst things that are not managed by JVM (Java Virtual Machine). There are some objects that aren’t eligible for the automatic garbage collection.

Hence knowing the memory management is essential as it will benefit the programmer to write high performance based programs that will not crash, or if does so, the programmer will know how to debug or overcome the crashes.

Introduction:

In every programming language, the memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. However in Java, unlike other programming language, the JVM and to be specific Garbage Collector has the role of managing memory allocation so that the programmer needs not to. Whereas in other programming languages such as C the programmer has direct access to the memory who allocates memory in his code, thereby creating a lot of scope for leaks.

The major concepts in Java Memory Management :

  • JVM Memory Structure
  • Working of Garbage Collector

Java Memory Structure:

JVM defines various run time data area which are used during execution of a program. Some of the areas are created by the JVM whereas some are created by the threads that are used in a program. However, the memory area created by JVM is destroyed only when the JVM exits. The data areas of thread are created during instantiation and destroyed when the thread exits.

JVM Memory area parts

JVM Memory area parts

Let’s study these parts of memory area in detail:

Heap :

  • It is a shared runtime data area and stores the actual object in a memory. It is instantiated during the virtual machine startup.
  • This memory is allocated for all class instances and array. Heap can be of fixed or dynamic size depending upon the system’s configuration.
  • JVM provides the user control to initialize or vary the size of heap as per the requirement. When a new keyword is used, object is assigned a space in heap, but the reference of the same exists onto the stack.
  • There exists one and only one heap for a running JVM process.

Scanner sc = new Scanner(System.in);

The above statement creates the object of Scanner class which gets allocated to heap whereas the reference ‘sc’ gets pushed to the stack.

Note: Garbage collection in heap area is mandatory.

Method Area:

  • It is a logical part of the heap area and is created on virtual machine startup.
  • This memory is allocated for class structures, method data and constructor field data, and also for interfaces or special method used in class. Heap can be of fixed or dynamic size depending upon the system’s configuration.
  • Can be of a fixed size or expanded as required by the computation. Needs not to be contiguous.

Note: Though method area is logically a part of heap, it may or may not be garbage collected even if garbage collection is compulsory in heap area.

JVM Stacks:

  • A stack is created at the same time when a thread is created and is used to store data and partial results which will be needed while returning value for method and performing dynamic linking.
  • Stacks can either be of fixed or dynamic size. The size of a stack can be chosen independently when it is created.
  • The memory for stack needs not to be contiguous.

Native method Stacks:

Also called as C stacks, native method stacks are not written in Java language. This memory is allocated for each thread when its created. And it can be of fixed or dynamic nature.

Program counter (PC) registers:

Each JVM thread which carries out the task of a specific method has a program counter register associated with it. The non native method has a PC which stores the address of the available JVM instruction whereas in a native method, the value of program counter is undefined. PC register is capable of storing the return address or a native pointer on some specific platform.

Working of a Garbage Collector:

  • JVM triggers this process and as per the JVM garbage collection process is done or else withheld. It reduces the burden of programmer by automatically performing the allocation or deallocation of memory.
  • Garbage collection process causes the rest of the processes or threads to be paused and thus is costly in nature. This problem is unacceptable for the client but can be eliminated by applying several garbage collector based algorithms. This process of applying algorithm is often termed as Garbage Collector tuning and is important for improving the performance of a program.
  • Another solution is the generational garbage collectors that adds an age field to the objects that are assigned a memory. As more and more objects are created, the list of garbage grows thereby increasing the garbage collection time. On the basis of how many clock cycles the objects have survived, objects are grouped and are allocated an ‘age’ accordingly. This way the garbage collection work gets distributed.
  • In the current scenario, all garbage collectors are generational, and hence, optimal.

Note: System.gc() and Runtime.gc() are the methods which requests for Garbage collection to JVM explicitly but it doesn’t ensures garbage collection as the final decision of garbage collection is of JVM only.

Knowing how the program and it’s data is stored or organized is essential as it helps when the programmer intends to write an optimized code in terms of resources and it’s consumption. Also it helps in finding the memory leaks or inconsistency, and helps in debugging memory related errors. However, the memory management concept is extremely vast and therefore one must put his best to study it as much as possible to improve the knowledge of the same.


Previous Article
Next Article

Similar Reads

How to find max memory, free memory and total memory in Java?
Although Java provides automatic garbage collection, sometimes you will want to know how large the object heap is and how much of it is left. This information can be used to check the efficiency of code and to check approximately how many more objects of a certain type can be instantiated. To obtain these values, we use the totalMemory() and freeMe
3 min read
Why Linked List is implemented on Heap memory rather than Stack memory?
Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind
14 min read
Demystifying Memory Management in Modern Java Versions
Memory management is the backbone of Java programming, determining how efficiently your applications use system resources. In this comprehensive guide, we will explore the intricacies of memory management in modern Java versions, including Java 8, 11, and beyond. By the end of this article, you'll have a profound understanding of how memory works i
6 min read
First Fit algorithm in Memory Management using Linked List
First Fit Algorithm for Memory Management: The first memory partition which is sufficient to accommodate the process is allocated.We have already discussed first fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.Examples: In
15+ min read
Program for Best Fit algorithm in Memory Management using Linked List
Best fit algorithm for memory management: The memory partition in which there is a minimum loss on the allocation of the process is the best-fit memory partition that is allocated to the process.We have already discussed one best-fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list
15+ min read
Program for First Fit algorithm in Memory Management
Prerequisite : Partition Allocation MethodsIn the first fit, the partition is allocated which is first sufficient from the top of Main Memory.Example : Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Block no. 1 212 2 2 417 5 3 112 2 4 426 Not AllocatedIts advantage is that it
8 min read
Program for Best Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsBest fit allocates the process to a partition which is the smallest sufficient partition among the free available partitions. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[] = {212, 417, 112, 426}; Output: Process No. Process Size Block no. 1 212 4 2 417 2 3 112 3 4 426 5 Implementa
8 min read
Program for Worst Fit algorithm in Memory Management
Prerequisite : Partition allocation methodsWorst Fit allocates a process to the partition which is largest sufficient among the freely available partitions available in the main memory. If a large process comes at a later stage, then memory will not have space to accommodate it. Example: Input : blockSize[] = {100, 500, 200, 300, 600}; processSize[
8 min read
Program for Next Fit algorithm in Memory Management
Prerequisite: Partition allocation methods What is Next Fit? The next fit is a modified version of 'first fit'. It begins as the first fit to find a free partition but when called next time it starts searching from where it left off, not from the beginning. This policy makes use of a roving pointer. The pointer moves along the memory chain to searc
11 min read
Best Fit Memory Management in Python
Memory management is a critical aspect of any programming language, and Python is no exception. While Python’s built-in memory management is highly efficient for most applications, understanding memory management techniques like the Best Fit strategy can be beneficial, especially from a Data Structures and Algorithms (DSA) perspective. This article
4 min read
Implementation of Worst fit memory management in Python
Worst Fit memory management is a memory allocation algorithm where the largest available block of memory is allocated to a process requesting memory. It aims to maximize the utilization of memory by allocating the largest available block to a process. Examples: Let's consider an example with memory blocks of sizes [100, 250, 200, 300, 150] and proc
2 min read
Implementation of First Fit Memory Management in Python
First Fit memory management is a technique used in operating systems for allocating memory to processes. When a process requests memory, the allocator searches the available memory blocks from the beginning of the memory and allocates the first block that is large enough to accommodate the process. Examples: Let's consider an example with memory bl
2 min read
Memory leaks in Java
In C, programmers totally control allocation and deallocation of dynamically created objects. And if a programmer does not destroy objects, memory leak happens in C, Java does automatic Garbage collection. However there can be situations where garbage collector does not collect objects because there are references to them. There might be situations
1 min read
Java substring() method memory leak issue and fix
String is a special class in Java. substring() is one of the widely used methods of String class. It is used to extract part of a string and has two overloaded variants: 1. substring(int beginIndex): This method is used to extract a portion of the string starting from beginIndex. Example: Java Code class GFG { public static void main(String args[])
4 min read
Thread Interference and Memory Consistency Errors in Java
Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables. When Two threads access the same shared memory This communication in multithreading ca
5 min read
What is Memory-Mapped File in Java?
Memory-mapped files are casual special files in Java that help to access content directly from memory. Java Programming supports memory-mapped files with java.nio package. Memory-mapped I/O uses the filesystem to establish a virtual memory mapping from the user directly to the filesystem pages. It can be simply treated as a large array. Memory used
4 min read
Heap and Stack Memory Errors in Java
Memory allocation in java is managed by Java virtual machine in Java. It divides the memory into stack and heap memory which is as shown below in the below media as follows: Stack memory in Java It is the temporary memory allocation where local variables, reference variables are allocated memory when their methods are called. It contains references
5 min read
Where is the memory allocated for Arrays in Java?
Each time an array is declared in the program, contiguous memory is allocated to it. Array base address: The address of the first array element is called the array base address. Each element will occupy the memory space required to accommodate the values for its type, i.e.; depending on the data type of the elements, 1, 4, or 8 bytes of memory are
3 min read
Best Practices For Automation Tester to Avoid Java Memory Leak Issue
A memory leak is a type of issue that will not cause any problem unless Java Heap Memory is overflown, but once you start getting this issue during execution, it’s very difficult to find out the root cause of it. So, it’s better to prevent memory leak issues in code from the very beginning. While building a test automation framework using Java, we
10 min read
Memory Game in Java
The Memory Game is a game where the player has to flip over pairs of cards with the same symbol. We create two arrays to represent the game board: board and flipped. The board is an array of strings that represents the state of the game board at any given time.When a player flips a card, we replace the corresponding element of the board array with
3 min read
Foreign Function and Memory API in Java
Foreign Function Interface (FFI) and Memory API in Java provide mechanisms for Java programs to interact with code written in other languages, such as C or C++. This allows developers to leverage existing native libraries or access low-level system functionality. FFI enables Java programs to call native functions, while the Memory API allows effici
3 min read
How are Java objects stored in memory?
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only declare a variable of a class type, only a reference
3 min read
How to Optimize Memory Usage and Performance when Dealing with Large Datasets Using TreeMap in Java?
Java programs' memory utilization and performance depend on their ability to handle huge datasets effectively. TreeMap is a Red-Black tree-based Map interface implementation that can be efficiently tuned to handle big datasets. This post examines techniques for maximizing speed and memory use using TreeMap to handle big datasets. TreeMap Overview:
2 min read
How to Create and Manipulate a Memory-Mapped File in Java?
The Memory-mapped files in Java offer a powerful mechanism to map a region of a file directly into the memory providing efficient access to file data. This method enhances the performance when dealing with large files or when frequent access to the file data is required. Syntax:The key method involved in the memory mapping of a file in Java is File
2 min read
How to Optimize Memory Usage and Performance for large HashSet Datasets in Java?
HashSet is mainly used for the data structures in Java offers fast access and prevents duplicate elements. So, the size of the dataset will be improved and it can raise memory consumption and performance issues. Now we are discussing exploring the various strategies to optimize memory usage and enhance performance. When we work with the large HashS
3 min read
java.lang.management.ThreadInfo Class in Java
java.lang.management.ThreadInfo class contains methods to get information about a thread. This information includes: Thread IDThread NameState of the ThreadStack trace of the ThreadThe object upon which the Thread is blockedList of object monitors that are blocked by the ThreadList of ownable synchronizers blocked by the ThreadNumber of times the T
4 min read
java.lang.management.ManagementPermission Class in Java
java.lang.ManagementPermission Class contains abstract methods to determine access to a system resource. Every object has some name. Most permission object also has some "actions" associated with it that tells which activities are permitted by this permission object. Class declaration : public final class ManagementPermission extends BasicPermissio
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Memory representation of Binomial Heap
Prerequisites: Binomial Heap Binomial trees are multi-way trees typically stored in the left-child, right-sibling representation, and each node stores its degree. Binomial heaps are collection of binomial trees stored in ascending order of size. The root list in the heap is a linked list of roots of the Binomial heap. The degree of the nodes of the
2 min read
Illustrate the difference in peak memory consumption between DFS and BFS
To understand this let's take a binary tree If we conduct BFS in this tree: In level 0 there is one node in the memory In level 1 there are two nodes in the memory In level 2 there are four nodes in the memory In level 3 there are eight nodes in the memory But in the case of DFS in this tree, you'll never have more than 4 nodes in memory The differ
1 min read
Article Tags :
Practice Tags :