Object Oriented Programming

 

 

Topic:  Memory Management In Java

 

Domain - Blog

 

 

 


Introduction

 Any computer program we write needs basic essential resources like CPU for math & computing, and finally memory for managing the data. Memory is a limited resource and it has to manage effectively.

For memory management in Java, we need to first understand how the memory is allocated, referenced, de-allocated, and finally, what happens to the memory after de-allocation. Once the memory de-allocated, the memory would be marked free for future usage.

In Java, if the memory is allocated to a variable and the variable is still referencing it, the memory would be allocated not available for other variables/program. Hence, if a code is written to allocate a resource for usage with no clean-up after the job done, the allocated memory unit would be locked forever leading to a memory leak, eventually, leading to an error called  ‘java.lang.OutOfMemoryError’. java

Java does memory management automatically and that system is known as ‘Garbage Collector’ .Java memory management divides into two major parts:

A) JVM Memory Structure

B) Garbage Collector

 

JVM Memory Structure:

        JVM creates various run time areas during the startup for the execution of the program. The following figure illustrates the memory model used by JVM.





Method Area

Method area is the space where the compiled code of all the JVM Threads contain. It stores the data common to all the threads like methods, constructors of each class, common run time variables etc. Its very similar to  Heap memory but this area couldn't get compact or clean up during the garbage collection. It is created during the startup of JVM.

 

 

 Java Stack

In other words, its JVM private method stack. This is same as Conventional method stack but used for only methods created in Java.

·If methods require a large amount of stack than supplied, it raises StackOverflowError

·If memory can be extended but couldn't able to allocate, it raises OutOfMemoryError

 

 

pc Register

As Java can execute multi-threads, each thread has it's own pc register to store the current instruction being executed by the thread. It contains the value only the thread is executing a non-native instruction. If the thread is executing a native instruction, it will be undefined.

 

 

Heap

Heap is the common run time work area for all the threads. It stores the local variables, collections, objects data being used by the each thread.  The reclaimed objects will be collected/removed by the automatic memory management process called Garbage Collector. The head size can be fixed by using the command line parameters otherwise it's not limited (depends on the system where the JVM is running).
To increase the performance of the JVM, the heap is divided into multiple generation. So Heap is divided into Young generation and Old or Tenured Generation

 PermGen space will be used by JVM to keep the loaded class and other common spaces like String pool. This space is directly proportional to the size of the application (classes, strings created etc.) and also GC cannot do much clean-up on this, so it will easily run out of memory with PermGen out of space error if not defined properly.

 Heap and PermGen space can be configurable using command line arguments while starting the JVM.

 

 

Garbage Collector:

What is Garbage Collection in Java?

In Java, programmers face the issue of having to destroy the objects that are out of use. But with the Garbage Collector, this can be easily taken care of. The main objective of this Garbage Collector is to free heap memory by destroying the objects doesn’t contain a reference. The technique is known as Garbage Collection.

It is also considered as a program that helps to perform automatic memory management. When Java Programs are run on the JVM, objects are created on the heap, which is actually a portion of memory that is dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up some memory.

· Programs that do not de-allocate memory can eventually break when there is no memory left in the system to allocate. All these programs are said to have memory leaks.

· Garbage collection in Java happens automatically during the lifetime of a program, eliminating the necessity to de-allocate memory and therefore avoiding memory leaks.

· Methods like free() in C and delete() in C++ are used but, in Java, it is performed automatically. So, Java provides better memory management.

 

 

How does Garbage Collection work?

Garbage Collection is a process of working with the Heap memory and also mark or identify the unreachable objects and destroy them with compaction.

Garbage collection in Java is an automatic process and the programmer does not have to explicitly mark objects to be deleted. The implementation mainly lives in the JVM Each JVM can implement garbage collection.  The only requirement is that it should meet the JVM specification.

Even though there are many JVMs available,Oracle Hotspot is by far the most common as it offers a robust and mature set of garbage collection options.

·The HotSpot has several garbage collectors that are optimized for various use cases, and all the garbage collectors follow the same basic process.

·In the very first step, unreferenced objects are identified and marked as ready for garbage collection.

·In the second step, the marked objects are deleted. Optionally, memory can be compacted after the garbage collector deletes objects, so remaining objects are in a contiguous block at the start of the heap. The compaction process makes it easier to allocate memory to new objects sequentially after the block of memory allocated to existing objects.

All of HotSpot’s garbage collectors implement a generational collection strategy that categorizes objects by age. The rationale behind generational garbage collection is that most objects are short-lived and will be ready for garbage collection soon after creation.

Now let’s see what are the different types of garbage collectors.

 

 

Types of Garbage Collector

The JVM provides four different garbage collectors, all of them generational. Each one has its own advantages and limitations. The choice of which garbage collector to use lies with the user and there can be numerous differences in the throughput and application pauses.

There are namely 4 types of garbage collectors.

·Serial Garbage Collector (GC): All the garbage collection events are conducted serially in one single thread. Compaction is executed after each garbage collection.

·Parallel/throughput GC: Multiple threads are used for minor/small garbage collection. A single thread is used for major garbage collection and Old Generation compaction. Also, the Parallel variant uses multiple threads for major garbage collection and Old Generation compaction.

·CMS Collector: Multiple threads are used for small/minor garbage collection using the same algorithm as Parallel. Majority of the garbage collection is multi-threaded, but CMS runs concurrently along with the application processes to minimize application events. No compaction is performed.

·G1 Collector: This garbage collector is basically intended as a replacement for CMS. It is parallel and concurrent like CMS, but it works quite differently when it is compared to the older garbage collectors.

 

 

Advantages

·The biggest benefit of Java garbage collection is that it automatically handles the deletion of unused objects or some objects that are inaccessible to free up memory resources.

·Garbage Collection is now a new standard component of many popular programming languages.

·It makes Java memory-efficient. It is because the garbage collector removes the unreferenced objects from heap memory.

·It is automatically done by the garbage collector which is a part of JVM.

      

References –

1) http://codingthis.com/languages/java/demystifying-memory-management-java/

2) https://stackoverflow.com/questions/41120129/java-stack-and-heap-memory-management

3) http://kveeresham.blogspot.com/2014/09/java-memory-management-overview.html

4) https://www.javatpoint.com/memory-management-in-java

5)https://www.geeksforgeeks.org/java-memory-management/


Comments

Post a Comment