×

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things that are managed by JVM (Java Virtual Machine).

It is necessary for a programmer to understand the working of memory management to create a high performance-based program that will not crash or if got crashes, they will be aware of how to debug and overcome from the crash.

In every coding language, memory management plays a vital role in the allocation and deallocation of memory areas because it needs critical care. In Java, the JVM and the Garbage Collector manage the memory allocation.

Structure of Java Memory Areas

The JVM defines various runtime data areas that are used when we run our code. Some of the data areas are created when JVM starts and destroyed in the presence of JVM, and data areas created during the initialization of the thread get destroyed when the thread exists.

Heap:

  • The heap represents the runtime data area that stores the actual object in the memory. It is created during the virtual machine start-up.
  • The memory is allocated to every class instance. The size of the heap depends upon the system’s configuration.
  • When a new keyword is used, the object is assigned a memory area in a heap, but the reference of the object exists in the stack.

Method Areas

  • Method area stores class structures, method data, and constructor field data, including the special methods used in class.
  • It is created when the JVM starts.
  • Method area is logically a part of the heap area, but it may or may not be garbage collected.
  • The size of the method may be fixed or expanded as required by the computation and contracted if the method area is in use unnecessarily.

JVM Stacks

  • Each and every thread has its own stack created at the same time as that of the thread.
  • Every stack is classified into different parts called frames. These frames are used to store data and partial results and to perform dynamic linking, return value for methods, and dispatch exceptions.
  • Each and every stack’s frame is divided into three different parts.
    • Local variable storage area
    • Operand stack
    • Frame data.
  • All the local variables going to be stored in the Local variable storage area, any operations on the top of the variable that are going to be processed are stored in the Operand stack, and if any exception occurs during method execution, then those exceptions are going to be stored in the frame data.
  • Stacks may be of fixed size or dynamic. It can be chosen independently during the stack creation.

Native Method Stacks

Native Method Stacks are stacks written in a different language other than the Java Programming language. These memory areas are typically allocated to each thread when threads are created. The size of this this memory area can be fixed or dynamic.

Program Counter (PC) registers

  • It stores the address of the Java virtual machine instruction, which is currently executing.
  • In Java, every thread has its own pc register.
  • As a Java application contains some native libraries. If the method in the application is not native (i.e., written in Java) then the program counter contains the address of the JVM instruction currently being executed, and if it is native, then the PC register’s value is undefined.

Working of Garbage Collector

JVM uses this process to automatically allocate and deallocate the memory. The Garbage Collector works in below three steps below.

Marking- identifies what are the object not in use

Normal Deletion- The identified objects that are not in use has been removed from the heap.

Deletion and Compacting- Once the unused object is removed from the heap, the memory is allocated automatically, these memory allocations are grouped together so that in future the memory allocation will be faster.

Compacting helps us group the memory together, so the allocation of new memory will be increased.

Types of Garbage Collector

Serial Garbage Collector- It works by holding all the application threads. It works with single threaded environments. It has a major drawback of freezing all the application threads during garbage collection. That is why it is not suitable for the server environment. We may use it only for simple command-line programs.

Parallel Garbage Collector- It is also called the throughput collector. It is JVM’s default garbage collector. It uses multiple threads for garbage collection, but it also freezes all the application threads while performing garbage collection.

CMS Garbage Collector- CMS stands for Concurrent Mark Sweep. It uses multiple threads to scan the heap memory for the unused objects and then removes the marked instance. It holds the application threads while marking the referenced object in the tenured generation space and if there is any chance in heap memory in parallel while doing the garbage collection.

As compared to the parallel garbage collector, it uses more CPU to ensure better application throughput.

G1 Garbage Collector: It is used when there is a large heap memory area. G1 separates the heap memory into regions and groups the unused memory area in parallel. It also compacts the free heap space on the go just after reclaiming the memory.

System.gc() and Runtime.gc() are the methods that request for garbage collection to the Java Virtual Machine explicitly.

Multiple Choice Questions

1. Which memory area in Java stores objects at runtime?

A) Stack

B) Heap

C) Method Area

D) Program Counter

Answer: B) Heap

2. What does the Program Counter (PC) register store?

A) Local variables

B) Address of the currently executing JVM instruction

C) Garbage-collected objects

D) Native method references

Answer: B) Address of the currently executing JVM instruction

3. Which of the following garbage collectors is the default in JVM?

A) Serial Garbage Collector

B) CMS Garbage Collector

C) Parallel Garbage Collector

D) G1 Garbage Collector

Answer: C) Parallel Garbage Collector

4. What is the primary drawback of the Serial Garbage Collector?

A) It consumes too much memory

B) It freezes all application threads during garbage collection

C) It does not remove unused objects

D) It cannot handle large applications

Answer: B) It freezes all application threads during garbage collection

5. Which garbage collector is suitable for large heap memory areas?

A) CMS Garbage Collector

B) G1 Garbage Collector

C) Parallel Garbage Collector

D) Serial Garbage Collector

Answer: B) G1 Garbage Collector

6. What is stored in the JVM method area?

A) Object instances

B) Method data, class structures, and constructor fields

C) Local variables

D) Stack frames

Answer: B) Method data, class structures, and constructor fields

7. Which of the following methods explicitly request garbage collection in Java?

A) System.free()

B) Runtime.collect()

C) System.gc() and Runtime.gc()

D) Memory.clean()

Answer: C) System.gc() and Runtime.gc()

8. How does Compacting help in garbage collection?

A) It marks unused objects

B) It removes unused objects

C) It groups free memory areas together for faster allocation

D) It prevents objects from being garbage collected

Answer: C) It groups free memory areas together for faster allocation


Related Topics

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java Integer rotateRight() method

The rotateRight() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value right by the specified number of bits. Syntax public...

1 minute read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.