Home > Java > javaTutorial > body text

Heap and stack memory errors in Java

PHPz
Release: 2023-09-01 20:09:11
forward
1237 people have browsed it

Heap and stack memory errors in Java

In Java, every interface, class, object, variable and method of a running program is stored in a different location in the computer's memory. The heap is the part of the memory area where the values ​​of variables, methods, and classes are stored at runtime. Its allocation occurs dynamically and can grow or shrink based on the needs of the application. On the other hand, the names of reference variables, methods and classes are stored in the stack memory area. However, if their allocation is not handled correctly for some reason, it can lead to memory errors that we will discuss in this article.

Stack-related errors

Whenever a process starts, it automatically defines a fixed stack size. During each method call, a call frame is created on the call stack and lasts until the method call ends. We encounter a StackOverflowError when there is no room left in the stack space of the computer's memory for a new stack frame.

Example 1

The following example illustrates StackOverflowError

import java.lang.StackOverflowError;
public class Overflw {
   public static void methodA(int n1) {
      n1++;
      methodB(n1);
   }
   public static void methodB(int n1) {
      n1++;
      methodA(n1);
   }
   public static void main(String []args) {
      int n1 = 0;
      methodA(n1);
   }
}
Copy after login

Output

Exception in thread "main" java.lang.StackOverflowError
at Overflw.methodB(Overflw.java:10)
at Overflw.methodA(Overflw.java:6)
at Overflw.methodB(Overflw.java:10)
at Overflw.methodA(Overflw.java:6)
at Overflw.methodB(Overflw.java:10)
at Overflw.methodA(Overflw.java:6)
at Overflw.methodB(Overflw.java:10)
Copy after login

As you can see the output of the example 1 code, we received a StackOverflowError. Here, we have created two parameterized user-defined methods named "methodA" and "methodB". In the main method, we declare the integer variable "n1" and initialize it to 0, and call "methodA" with the parameter "n1". Now, "methodA" calls "methodB" and increments the value of "n1". Likewise, "methodB" calls "methodA" and this process repeats multiple times. So, at some point, the stack size created for this program gets exhausted, resulting in the following error.

We can take the following measures to handle StackOverflowError

  • Provide appropriate termination conditions for repeated methods

  • Reducing the size of local variables or arrays may also help.

  • Refactor code to avoid infinite method calls.

Example 2

Now, with the help of this example, we will try to find the solution for StackOverflowError Happened in the previous example.

public class Overflw {
   public static void methodA(int n1) {
      n1++;
      methodB(n1);
   }
   public static void methodB(int n1) {
      n1++;
      int n2 = 5;
      int mult = n1 * n2;
      System.out.println("Value of n1 and n2 multiplication is: " + mult);
  }
  public static void main(String []args) {
     int n1 = 0;
     methodA(n1);
   }
}
Copy after login

Output

Value of n1 and n2 multiplication is: 10
Copy after login

In example 1, the problem with the code is that lines 6 and 10 do not terminate. But in the above example, we gave a statement that terminates the program and prints the value stored in "mult".

Heap related errors

The "-Xmx" and "-Xms" properties of the JVM determine the size of the Heap. This size affects the storage of values. When the JVM encounters problems with value allocation due to insufficient space in part of the heap memory, we encounter OutOfMemoryError

Example 1

The following example illustrates OutOfMemoryError.

public class MemoryErr {
   public static void main(String[] args) {
      String stAray[] = new String[100 * 100 * 100000];
   }
}
Copy after login

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at MemoryErr.main(MemoryErr.java:3)
Copy after login

In the above code, the size we allocated is larger than the heap size, therefore, we get the OutOfMemoryError

We can take the following measures to handle OutOfMemoryError.

  • We can use the -Xmx and -Xms JVM options to increase the heap size

  • Using a garbage collector appropriate to the application's behavior may also help.

Example 2

The following example illustrates how to handle OutOfMemoryError using try and catch blocks.

public class MemoryErr {
   public static void main(String[] args) {
      try {
         String stAray[] = new String[100 * 100 * 100000];
      } catch(OutOfMemoryError exp) {
         System.out.println("Application reached Max size of Heap");
      }
   }
}
Copy after login

Output

Application reached Max size of Heap
Copy after login

in conclusion

This article first explains the two memory spaces required by every Java program. In later sections, we discuss errors related to heap and stack memory

The above is the detailed content of Heap and stack memory errors in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template