14 August 2023

Memory Allocation In Java - learngreen.net

Memory Management in Java

  The process of allocating dedicated virtual memory regions to computer programs and services is known as memory allocation in Java. The memory is separated into Stack and Heap Memory by the Java Virtual Machine. For the Java Virtual Machine, the stack and heap memory can be used to execute a program to its fullest extent. Memory is allocated for these operations each time a new variable or object is declared.

  Let's review the fundamentals of the Java memory structure before you can comprehend how memory is managed in Java. Memory in programming languages refers to the locations where values, instructions, or data are kept. Java has two different forms of memory heap memory and stack memory. The RAM or physical space that is allotted to different Java objects while they are running is known as stack memory. It is made to allocate static memory prior to thread execution. The values in the stack memory are transient and method-specific. It is based on the Last-in-first-out (or LIFO) ordering system. When we call a method, the stack memory creates a new block. It preserves nearby primitive values. The block that was formed in the stack memory is left empty after the method is ended.

 The location where all Java objects are stored is called heap memory. The heap space is created by the JVM for Java. The duration of the application's runtime is spent using heap space by the program. A number of generations are further separated into the heap space. New objects are kept in the heap area for the Young generation. The older generation comes next. In the younger generation, everything has a timetable. The objects are transferred to the older generation after the timeline is finished. The metadata for runtime classes and application methods are stored in the permanent generation, which is the last. The heap space grows up as more Java objects are created, necessitating the use of additional RAM. In order to make room in the memory system for new items, we must free up heap space. Managing memory is what this entails. To put it simply, Java memory management is the process of allocating memory to new Java objects. During memory management, unused Java objects are removed to create way for fresh ones.

Memory Management:-

The fact that Java programmers do not have to worry about memory management is one of the language's major benefits.  Garbage collection, a Java feature that provides autonomous memory management, handles this task. Java's memory management system is divided into two primary parts

1. Java Virtual Machine (JVM): JVM can be thought of as an engine or a software that gives Java bytecodes a runtime environment. The bytecodes are converted into computer language. In the heap space, a memory is created. The JVM shuts down, erasing this memory.

2. Garbage collector:- When the heap memory is completely used up, the garbage collection procedure begins. The items that are no longer needed are automatically destroyed by the garbage collector. As a result, it makes room in memory for the allocation of new objects. The memory from the older generation is often cleared by the garbage collector.

  JVM, or the Java virtual machine, is the standard that offers a runtime environment to execute bytecode, as was previously stated. Memory management is one of its key features. Every time we use a new keyword, JVM creates runtime areas in the heap structure and gives instances for an object in the heap. It is necessary for heap memory allocation.
  The process of allocating or assigning memory to different Java objects is known as Java memory allocation, as the name suggests. In this operation, program virtual memory blocks are set aside. The JVM accomplishes this. In Java, memory can be allocated in one of two ways

Java's static memory allocation requires the declaration of the variables prior to program execution. At compile time, static RAM is allotted.

Java's dynamic memory allocation:- Java objects are given memory during runtime or execution time, which is known as dynamic memory allocation. The opposite of static memory allocation, it. The heap space is where dynamic memory allocation happens. New objects are always produced in the heap area, and the stack memory stores the references to such items.

Java's Stack Memory allocation is utilized for both thread execution and static memory. Due to the Last-In-First-Out nature of references, the values stored in this memory are transient and restricted to particular methods.

  The stack memory holds primitive data and references until the method is finished after the memory is called and a new block is formed there. When a process ends, the block is flushed and ready for a new one to begin. In comparison to the heap memory, the overall size of the stack memory is typically negligible. 

The size of the stack memory might change as new methods are called and returned as necessary.

As long as the method's scope is present, any variable in the stack may be used.

As soon as a method is executed, it receives auto-allocation and deallocation. 

The Java.lang.StackOverFlowError occurs when the RAM is full.

In terms of access speed, it is quicker than heap memory.


Methods Used in Stack Memory:-
Pushing an object to the top of the stack is done with this method.
Object pop() flushes and returns any element that is at the top of the stack. The EmptyStackException exception happens if a stack is empty when pop() is called. 
Using the object peek( ) method, the top element is returned without being flushed.
Boolean empty( ):- The function returns 1 (true) if the loop's stack is empty of top values, and 0 (false) otherwise.
To determine whether an object is present in the stack, use search(Object element). The function returns the location of the element from the top of the stack if the value is discovered; else, it returns -1.

Heap Memory:-
Every time an object is formed and allocated in it, Java Heap Space—which is mostly used by the Java runtime—comes into play. Similar to garbage collection, the discrete function continuously flushes the memory utilized by earlier instances without references. For an item made in the heap space, access is unrestricted throughout the application. 
Java divides memory allocation into four categories: heap, stack, code, and static.

Including the Young Generation, Old or Tenured Generation, and Permanent Generation, accessible through the complex memory management technique.
When the heap memory is full, the method returns a java.lang.OutOfMemoryError.
This memory's access time is noticeably longer than the stack memory's.
The memory must be cleared of foreign items using a similar function to Garbage Collector because it does not undergo automated deallocation.

Stack memory is used to store primitive data types like int, double, char, etc. They are simple to manage and come in predetermined sizes.



 package Java;
 public class Example {
 public static void main(String[] args) {
 int num = 84; //Stored in Stack
 System.out.println(num);
	}
  }
  

The new keyword in Java is used to create objects, which are then placed in the heap memory. Memory allocation and garbage collection for objects that are no longer referenced are handled by the JVM.



  package Java;
 public class Example2 {
 public static void main(String[] args) {
 // Created Object in Heap
 String message = new String("Hi!");
 System.out.println(message);	 
	  }
    }
 

 

Java variables that store objects store pointers to the actual objects that are stored in memory. While the real object is kept in the heap, this reference is kept in the stack memory.



  package Java;
  public class Example3 {
  public static void main(String[] args) {
  String greeting = "Welcome!";
  // Reference points to the same object
  String reference = greeting;
  System.out.println(reference);
	}
 }
 

In Java, arrays are objects, and the heap is where their memory allocation takes place. Multiple values of the same type are progressively stored in memory using arrays.



  package Java;
 public class ArrayDemo {
 public static void main(String[] args) {
 // Array of 3 integers	 
 int[] numbers = new int[3];
 numbers[0] = 8;
 System.out.println(numbers[0]);
	}
 }
 

The garbage collector automatically deals with unreferenced items.



  package Java;
  public class Example4 {
  public static void main(String[] args) {
  /* Created but not referenced
  * At some point, the garbage
  * collector will free memory occupied by 
  * unused Object 
  */
  String name = new String();
	 }
   }
   

 

No comments:

Post a Comment