Java Program to Set Minimum and Maximum Heap Size


The Java heap is a particular memory area which is used to store the objects and represent them as or by an instance in Java Virtual Machine. The Java heap can be shared between two threads as long as the environment is occupied by some running applications. The heaps are sorted in a stack memory and follow the Last In First Out (LIFO) method after the creation of an object in JVM.

When the size of a heap memory is compared to stack, the spare objects are cleared by the GarbageCollector automatically. The heap memory are divided into three parts in Java −

  • New Heap Generation

  • Old Heap Generation

  • Permanent Heap Generation

The New Heap Generation − A newly created objects allocated in the memory during the particular operation.

  • It has two main parts - Eden and Survivor. The second part can be divided into two parts, as Survivor1 and Survivor2.

  • The newly created objects are handled by Eden function space.

  • If the Eden is full, a minor garbage collection will happen and live objects will moved to the Survivor division.

  • After the operation in Survivor the whole node will be transferred to the Old Heap Generation.

The Old Heap Generation − When the allocated age is matched for the new generation, they are moved to the old generation part. It is a memory community of long-surviving objects. The major garbage collection operation runs on the old generation part to collect some dead objects

The Permanent Heap Generation − To store the metadata we can use the permanent generation. It is a process of the class and method bundle. Java virtual machine has also a full directory for the permanent generation. The garbage in this space cleaned by a part of full garbage collection operation.

Algorithm to set minimum and maximum heap size in Java

  • Step 1 − Start

  • Step 2 − Declare an array.

  • Step 3 − Start sorting from index 1.

  • Step 4 − Do not start sorting from 0.

  • Step 5 − Left Child is at [2*i] if available.

  • Step 6 − Right child is at [2*i+1] if available.

  • Step 7 − Parent Node is at [i/2] if available.

  • Step 8 − Terminate

Syntax

Heapify(array, size, i)
  set i as largest
  leftChild = 2i + 1
  rightChild = 2i + 2
  
  if leftChild > array[largest]
set leftChildIndex as largest
  if rightChild > array[largest]
set rightChildIndex as largest

  swap array[i] and array[largest]

MaxHeap(array, size)
  loop from the first index of non-leaf node down to zero
call heapify

For Min-Heap operation, leftChild and rightChild both will must be larger than the parent for all.

Here in this syntax, we have applied the heap logics to build up a Java code to set minimum and maximum heap size. Here are two possible functions we have −

  • wrapper.java.initmemory - The minimum heap size. The default value is 256 MB.

  • wrapper.java.maxmemory-The maximum heap size. The default value is 1024 MB.

Approaches to follow

  • Approach 1 − Java program to display the heap memory statistics

  • Approach 2 − Java program by using -Xmx to set maximum heap size to maximum

  • Approach 3 − Java program by using -Xms to set a minimum or initial heap size

Java program to display the heap memory statistics

Here we have written the Java program by which we can display the heap memory statistics. Have a look.

Example 1

import java.io.*;
import java.lang.*;
import java.util.*;
public class heapMemorybytp {
   public static void main(String[] args){
      double mb = 1000000;
      Runtime r = Runtime.getRuntime();
      System.out.println("Max memory alloted"+ " " + r.maxMemory() / mb);
      System.out.println("Initial memory present"+ " " + r.totalMemory() / mb);
      System.out.println("Free memory available"+ " " + r.freeMemory() / mb);
      System.out.println("Consume memory by the process"+ " "+ (r.totalMemory() - r.freeMemory()) / mb);
   }
}

Output

Max memory alloted 1073.741824
Initial memory present 270.532608
Free memory available 268.466176
Consume memory by the process 2.066432

Java program by using -Xmx to set maximum heap size to maximum

If we want to set the maximum heap value in Java, there we have the -Xmx option to the Java interpreter.

Operations on Max Heap as follows −

  • getMax() − It returns the root element as Max. The Time Complexity of this operation is O(1).

  • extractMax() − Removes the maximum element from MaxHeap. The Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property by calling the heapify() method after removing the root.

  • insert() − Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If the new key is smaller than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

Example 2

import java.io.*;
import java.lang.*;
import java.util.*;
public class heaptheMemorybytp {
   public static void main(String[] args){
      double mb = 10000000;
      Runtime r = Runtime.getRuntime();
      System.out.println("Max memory alloted here" + " " + r.maxMemory() / mb);
      System.out.println("Initial memory we have here available" + " " + r.totalMemory() / mb);
      System.out.println("Free memory we have now" + " " + r.freeMemory() / mb);
      System.out.println("Consumed memory by the process"+ " "+ (r.totalMemory() - r.freeMemory()) / mb);
   }
}

Output

Max memory alloted here 107.3741824
Initial memory we have here available 27.0532608
Free memory we have now 26.8466176
Consumed memory by the process 0.2066432

Example 2 A

public class maxHeapoperation {
   public int capacity;
   public int [] mH;
   public int currentSize;
   public maxHeapoperation(int capacity){
      this.capacity=capacity;
      mH = new int [capacity+1];
      currentSize =0;
   }
   public void createHeap(int [] arrA){
      if(arrA.length>0){
         for(int i=0;i<arrA.length;i++){
            insert(arrA[i]);
         }
      }
   }
   public void display(){
      for(int i=1;i<mH.length;i++){
         System.out.print(" " + mH[i]);
      }
      System.out.println("");
   }
   public void insert(int x) {
      if(currentSize==capacity){
         System.out.println("heap is full");
         return;
      }
      currentSize++;
      int idx = currentSize;
      mH[idx] = x;
      bubbleUp(idx);
   }
   public void bubbleUp(int pos) {
      int parentIdx = pos/2;
      int currentIdx = pos;
      while (currentIdx > 0 && mH[parentIdx] < mH[currentIdx]) {
         swap(currentIdx,parentIdx);
         currentIdx = parentIdx;
         parentIdx = parentIdx/2;
      }
   }
   public int extractMax() {
      int max = mH[1];
      mH[1] = mH[currentSize];
      mH[currentSize] = 0;
      sinkDown(1);
      currentSize--;
      return max;
   }

   public void sinkDown(int k) {
      int greatest = k;
      int leftChildIdx = 2 * k;
      int rightChildIdx = 2 * k+1;
      if (leftChildIdx < heapSize() && mH[greatest] < mH[leftChildIdx]) {
         greatest = leftChildIdx;
      }
      if (rightChildIdx < heapSize() && mH[greatest] < mH[rightChildIdx]) {
         greatest = rightChildIdx;
      }
      if (greatest != k) {
         swap(k, greatest);
         sinkDown(greatest);
      }
   }
   public void swap(int a, int b) {
      int temp = mH[a];
      mH[a] = mH[b];
      mH[b] = temp;
   }
   public boolean isEmpty() {
      return currentSize == 0;
   }
   public int heapSize(){
      return currentSize;
   }
   public static void main(String args[]){
      int arrA [] = {16,10,97,7,10,2001,31,10,22};
      System.out.print("Original Array Is Here: ");
      for(int i=0;i<arrA.length;i++){
         System.out.print("" + arrA[i]);
      }
      maxHeapoperation m = new maxHeapoperation(arrA.length);
      System.out.print("\nMax-Heap After Operation : ");
      m.createHeap(arrA);
      m.display();
      System.out.print("Extract Max Hep After Operation:");
      for(int i=0;i<arrA.length;i++){
         System.out.print("" + m.extractMax());
      }
   }
}

Output

Original Array Is Here: 16 10  97  7  10 2001  31  10 22
Max-Heap After Operation : 9722 31107 1016 010
Extract Max Hep After Operation:9731  221610  101070

Java program by using -Xms to set a minimum or initial heap size

If we want to set the minimum heap value in Java, there we have the -Xms option to the Java interpreter.

Operations on Mean Heap as follows −

  • getMin() − It returns the root element as Min. The Time Complexity of this operation is O(1).

  • extractMin() − Removes the minimum element from MinHeap. The Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing the root.

  • insert() − Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If a new key is larger than its parent, then we don’t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

Example 3

import java.io.*;
import java.lang.*;
import java.util.*;
public class heaptheMemorybytp {
   public static void main(String[] args){
      double mb = 10000000;
      Runtime r = Runtime.getRuntime();
      System.out.println("Max memory we have in hand"+ " " + r.maxMemory() / mb);
      System.out.println("Initial memory has given"+ " " + r.totalMemory() / mb);
      System.out.println("Free memory is available here" + " " + r.freeMemory() / mb);
      System.out.println("Consume memory by the process"+ " "+ (r.totalMemory() - r.freeMemory()) / mb);
   }
}

Output

Max memory we have in hand 107.3741824
Initial memory has given 27.0532608
Free memory is available here 26.8466176
Consume memory by the process 0.2066432

Example 3 A

public class minHeapoperation {
   public int capacity;
   public int [] mH;
   public int currentSize;
   public minHeapoperation (int capacity){
      this.capacity=capacity;
      mH = new int [capacity+1];
      currentSize =0;
   }
   public void createHeap(int [] arrA){
      if(arrA.length>0){
         for(int i=0;i<arrA.length;i++){
            insert(arrA[i]);
         }
      }
   }
   public void display(){
      for(int i=1;i<mH.length;i++){
         System.out.print(" " + mH[i]);
      }
      System.out.println("");
   }
   public void insert(int x) {
      if(currentSize==capacity){
         System.out.println("Heap is full. I Am Really Sorry Buddy!");
         return;
      }
      currentSize++;
      int idx = currentSize;
      mH[idx] = x;
      bubbleUp(idx);
   }

   public void bubbleUp(int pos) {
      int parentIdx = pos/2;
      int currentIdx = pos;
      while (currentIdx > 0 && mH[parentIdx] > mH[currentIdx]) {

         swap(currentIdx,parentIdx);
         currentIdx = parentIdx;
         parentIdx = parentIdx/2;
      }
   }

   public int extractMin() {
      int min = mH[1];
      mH[1] = mH[currentSize];
      mH[currentSize] = 0;
      sinkDown(1);
      currentSize--;
      return min;
   }

   public void sinkDown(int k) {
      int smallest = k;
      int leftChildIdx = 2 * k;
      int rightChildIdx = 2 * k+1;
      if (leftChildIdx < heapSize() && mH[smallest] > mH[leftChildIdx]) {
         smallest = leftChildIdx;
      }
      if (rightChildIdx < heapSize() && mH[smallest] > mH[rightChildIdx]) {
         smallest = rightChildIdx;
      }
      if (smallest != k) {

         swap(k, smallest);
         sinkDown(smallest);
      }
   }

   public void swap(int a, int b) {
      int temp = mH[a];
      mH[a] = mH[b];
      mH[b] = temp;
   }
   public boolean isEmpty() {
      return currentSize == 0;
   }

   public int heapSize(){
      return currentSize;
   }

   public static void main(String args[]){
      int arrA [] = {16,10,1997,7,10,2001,10,31,2022};
      System.out.print("Original Array Set Is Here, Have A Look : ");
      for(int i=0;i<arrA.length;i++){
         System.out.print("  " + arrA[i]);
      }
      minHeapoperation m = new minHeapoperation (arrA.length);
      System.out.print("\nMin-Heap Is Here Buddy : ");
      m.createHeap(arrA);
      m.display();
      System.out.print("Extract Min Heap After The Operation:");
      for(int i=0;i<arrA.length;i++){
         System.out.print("  " + m.extractMin());
     }
   }
}

Output

Original Array Set Is Here, Have A Look :16  10  1997  7  10  2001  10  31  2022
Min-Heap Is Here Buddy :  7 10 10 16 10 2001 1997 31 2022
Extract Min Heap After The Operation:  7  10  10  10  16  31  1997  2001  2022

Conclusion

In this article today, we have learned about the process to set minimum and maximum heap size with some possible java codes by following the syntaxes and algorithm. Hope this article helped you to understand the modus operandi of the heap size processes mentioned here.

Updated on: 12-Apr-2023

458 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements