Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Java Memory Management: Garbage Collection and Memory Optimization Techniques

Published On: May 18, 2023

The process of allocating and releasing space for objects is referred to as memory management in Java. Java maintains memory automatically. Java uses an autonomous memory management method known as the “garbage collector”. Consequently, our program does not need to integrate memory management logic. 

Now, we’re going to discuss Java’s memory management, the various memory components of the JVM, and monitoring and tuning for garbage collection. You can learn more about memory management through our Java Training in Chennai at SLA Institute.

Introduction to Memory Management in Java

Memory is a crucial resource and a precious resource in any computer language. As a result, memory must be carefully managed without any leaks. Memory allocation and deallocation is a crucial task that calls for much care and thought. Contrary to other programming languages, the JVM in Java, and specifically the garbage collector, manages memory allocation such that the programmer is not required to. 

Other programming languages, like C, give the programmer direct access to the memory as they allocate it, which leaves a lot of room for leaks.

Why is Learning Memory Management in Java Important?

Nobody denies the fact that Java manages memory on its own and doesn’t need a programmer’s explicit help. Garbage collection ensures that unused space is cleaned up and that memory may be released when not required. So what exactly does a programmer do, and why is it crucial that they comprehend Java Memory Management

Due to the garbage collector, programmers don’t have to worry about problems like object annihilation. However, an automatic garbage pickup may not always guarantee everything. We frequently find ourselves dealing with JVM (Java Virtual Machine)-managed objects if we don’t grasp how memory is controlled. 

All things cannot be automatically collected by garbage collection. Therefore, having a solid understanding of memory management is essential since it will enable programmers to build high-performance applications that don’t crash or, in the event that they do, know how to fix them.

Memory management is the process of creating room for new object allocations by allocating new objects and deleting old ones that are no longer needed. This section teaches the fundamentals of object allocation and garbage collection in the Oracle JRockit JVM as well as some fundamental memory management ideas.

The key concepts behind Java Memory Management are:

  • Java Memory Structure
  • Working of Garbage Collector

Java Memory Structure

Different run-time data areas that are utilized during program execution are defined by JVM (Java Memory Management). The threads that are employed in a program produce some areas, while the JVM creates others. However, the JVM’s memory structure is only deleted when it terminates. When a thread is instantiated, its data regions are formed, and they are removed when the thread terminates.

JVM Memory Structure

Method Area

Method Area is a part of the heap memory, which is shared by all threads. When the JVM starts, it creates. Class structure, superclass name, interface name, and constructor names are all stored there. The method region of the JVM stores the following types of data:

  • A type’s fully qualified name (for example, String).
  • The modifiers of the type
  • Direct superclass name of Type
  • A detailed list of super interfaces’ fully qualified names.
Heap Area

The actual items are kept in a heap. When the JVM starts, it creates. If necessary, the user has control over the heap. Its size might be either fixed or variable. When you use a new keyword, the JVM creates an instance of the object in a heap. While the object’s reference is kept in the stack. There is only one heap for each JVM process that is active. As soon as the mound is full, trash gets collected. 

The preceding statement produces a StringBuilder class object. The reference SB allocates to the stack, while the object allocates to the heap. The following sections make up a heap:

  • Young Generation
  • Survivor Space
  • Old Generation
  • Permanent Generation
  • Code Cache

Example

public class Employee 

{

  String fname;

  String lname;

  int age;

  Employee (String fname, String lname, int age) 

{

    this.fname = fname;

    this.lname = lname;

    this.age = age;

  }

  public static void main(String[] args) {

    Employee pr = new Employee(“Dev”, “Jony”, 30);

    System.out.println(p.firstname); //Dev

    System.out.println(p.lastname); // Jony

    System.out.println(p.age); // 30

  }

}

Stack Area

When a thread starts, the stack area is formed. It may be either fixed or variable in size. Each thread is allotted a specific amount of stack memory. It is used to store data and incomplete results. There are mentions of the items in the stack inside. In addition, it keeps the value itself rather than a reference to a heap object. The term “scope” refers to how visible the variables kept in the stack are.

Stack Frame: The data for the thread is stored in a data structure called a stack frame. The thread’s state in the current method is represented by thread data.
  • It is used to save data and partial results. Additionally, it handles dynamic linking, values returned by methods, and exception dispatch.
  • A new frame is created when a method is called. When the method call is finished, the frame is destroyed.
  • Each frame has its own Operand Stack (OS), Local Variable Array (LVA), and Frame Data (FD).
  • LVA, OS, and FD sizes are decided upon during compilation.
  • In every given thread of control, there is only ever one active frame (the frame for the method to execute). The current method is the one used by this frame, which is referred to as the current frame. The current class is the class of a method.
  • If the current method invokes another method or is finished, the frame terminates it.
  • A thread’s locally constructed frame is only accessible by that thread and cannot be accessed by any other threads.
Native Method Stack

Java does not support native method stacks, also referred to as C stacks. When a thread is created, it is given a memory allocation. Additionally, it could be of a fixed or dynamic character.

Program Counter (PC) Register

Each JVM thread that executes a particular method’s task is connected to a program counter register. While in a native method, the value of the program counter is unknown, a non-native method has a PC that contains the address of the accessible JVM instruction. A native pointer or the return address can be stored in a PC register depending on the platform.

Working of a Garbage Collector

Overview of Garbage Collector

Java programs use memory in a variety of ways as they run. The heap is where items are stored in memory. It is the only area of memory that participates in trash collection. It’s sometimes referred to as a “garbage collectible heap”. The heap has as much space as possible due to all the garbage collecting. Finding and removing things that are out of reach is the job of the garbage collector.

Object Collection

The JRockit JVM verifies the object’s size before allocating it. It makes a distinction between little and big items. The JVM version, heap size, garbage collection method, and platform utilized all influence the small and big sizes. An object’s size typically ranges from 2 to 128 KB.

The Thread Local Area (TLA), a free section of the heap, is where the little items are kept. There is no inter-thread synchronization in TLA. TLA requests a new TLA when it is filled.

Large items, however, that do not fit inside the TLA, are allocated directly to the heap. When a thread uses young space, it is immediately stored in old space. More synchronization between the threads is needed because of the huge object.

What functions does Java Garbage Collector have?

The JVM is in charge of the garbage collector. JVM determines when trash collection should take place. We can also instruct the JVM to start the trash collector. But there is never a guarantee that the JVM will follow the guidelines. When JVM notices that memory is running low, the garbage collector is launched. Requests for the garbage collector from Java programmes are frequently fulfilled rapidly by the JVM. It does not ensure that the demands will be fulfilled.

Find out which is the best programming language that satisfies your learning desire.

Types of Garbage Collection

The following are the five categories of garbage collection:

Serial GC: It employs the mark and sweeps method, or minor and major GC, for young and old generations.

Parallel GC: Similar to serial garbage collection, parallel garbage collection creates N (the number of CPU cores in the system) threads for new generation trash collection.

Parallel Old GC: The only difference between old GC and parallel GC is that old GC employs multiple threads for both generations.

Concurrent Mark Sweep (CMS) Collector: It takes care of the elderly generation’s waste collecting. Using the XX:ParalleCMSThreads=JVM option, you can restrict the number of threads in the CMS collection. Concurrent Low Pause Collector is another name for it.

G1 Garbage Collector: Java 7 saw its debut. Its goal is to take the place of the CMS collector. It is a concurrent, parallel, and CMS collector. There is no area for the young and senior generations. It separates the heap into several piles of equivalent size. The first regions to be gathered are those with the least live data.

Mark and Sweep Algorithm

The mark and sweep algorithm is used by JRockit JVM to carry out garbage collection. The mark phase and the sweep phase are two phases.

Mark Phase: Live objects are those that can be accessed by threads, native handles, and other GC root sources. There are multiple root items in every object tree. The root of Garbage Collection is always accessible. Consequently, any object with a garbage collection root at the root. All items that are in use are identified and marked; the remainder can be regarded as waste.

Java Mark Phase

Sweep Phase: To determine the space between the living objects, the heap is surveyed during this phase. These openings are noted in the free list and are accessible for the allocation of new objects.

Mark and Sweep have two upgraded iterations:

  • Concurrent Mark and Sweep
  • Parallel Mark and Sweep

Concurrent Mark and Sweep

It permits the threads to keep going for a sizable amount of garbage collection. Marking types are as follows:

Initial marking: It reveals the primary collection of active objects. While threads are paused, it is completed.

Concurrent marking: In this marking, references from the root set are fastened to.. The remaining living things are discovered and marked in a pile. While the thread is active, it is finished.

Pre-cleaning marking: This method shows the alterations brought about by concurrent marking. Other marked and discovered living things. While the threads are active, it is completed.

Final marking: The final marking shows the modifications made by the pre-cleaning marking. Other marked and discovered living things. While threads are paused, it is completed.

Parallel Mark and Sweep

In order to complete trash collection as quickly as feasible, it takes advantage of every CPU that is available on the system. The parallel trash collector is yet another name for it. When the simultaneous garbage collection runs, threads are not active.

Benefits of Sweep and Mark

  • It is a continuous procedure.
  • It is an endless circle.
  • No additional overheads are permitted while an algorithm is running.

Cons of Sweep and Mark

Wrapping Up

In Java, the term “memory management” refers to the allocation and release of memory for objects. There are two main sections in Java Memory Management:

  • JVM Memory Structure
  • Working of the Garbage Collector

In the Java programming language, threads communicate with one another through memory, as explained by the Java memory model. The JVM memory structure has several regions where the program objects are kept.

“Garbage collection” is the process of making room in the heap for the allocation of new objects.

It is time to accelerate your skills. Join SLA Institute for the Best Java Training in Chennai.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.