Memory Management in java: Memory Leak

             Memory leak occurs when a computer program doesn’t manage the Memory allocation. This causes a part of memory is allocated, but it is not freed. Even though, the memory is not needed.

Memory leak makes the system performance low. If the programming language is java, it mostly uses the garbage collector to manage the memory. 

Sometimes, few of object references are there unintentionally. This may cause memory leak.

For eg, let us consider an infinite loop.

  • Here, a list is created as String. Using a while loop, the elements are added.
  • But the loop is infinite. So, the list elements are added in infinite times.
  • So, garbage collector unable to reclaim the memory of ‘l1’. So, it causes memory leak.

Program: Memory Leak Example

Steps:

  • Include the built in packages java.util.ArrayList, java.util.List.
  • Create a public class with main () function.
  • A list l1 is created as String using ArrayList.
  • Create a while loop with true argument. Just the add the data to list ‘l1’.

Code:

import java.util.ArrayList;

import java.util.List;

public class MemoryLeakEg {

    public static void main(String[] args) {

        List<String> l1 = new ArrayList<>();

       //Infinite loop  

      while(true) {

            l1.add("Number: " + i);

          }

}

Some of the techniques are used to avoid the memory leak as follows…

Techniques to avoid memory leak:

Consider the references:

  First, avoid static references. It may hold the object for long time.

  Release the references whenever the objects are completed its process.

Resources:

 It can be used as “try-with-resources”. For eg: Streams

Profiling Tools:

 This is used to monitor the memory and find the potential leak.

The memory leak and the mechanisms used to handle the memory leak is coated with example.

No comments:

Post a Comment