Memory leaks in Java

JavaObject Oriented ProgrammingProgramming

In Java, garbage collection (the work of destructor) is done automatically using garbage collection. But what if there are objects that have references to them in the code? It can’t be de-allocated, i.e their memory can’t be cleared. If such a situation occurs again and again, and the created or referred objects are not used at all, they become useless. This is what is known as a memory leak.

If the memory limit is exceeded, the program gets terminated by throwing an error, i.e ‘OutOfMemoryError’. This is the reason why it is always suggested to remove all references to an object so that Java Garbage collector can automatically destroy it.

Below is an example that illustrates how the compiler runs out of space when too much memory is trying to be used −

Example

 Live Demo

import java.util.Vector;
public class Demo{
   public static void main(String[] args){
      Vector my_v1 = new Vector(314567);
      Vector my_v2 = new Vector(784324678);
      System.out.println("This is the last line to be printed");
   }
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.Vector.<init>(Vector.java:142)
at java.base/java.util.Vector.<init>(Vector.java:155)
at Demo.main(Demo.java:7)

A class named Demo contains the main function where two vector objects have been created by assigning them too large of a space. The last print line is just written to check if the compiler reaches that line. In reality, it doesn’t, since the space occupied by these vectors is huge and so much memory can’t be allocated, resulting in an error.

raja
Published on 07-Jul-2020 08:18:18
Advertisements