The Wayback Machine - https://web.archive.org/web/20241003005008/https://www.geeksforgeeks.org/understanding-outofmemoryerror-exception-java/
Open In App

Understanding OutOfMemoryError Exception in Java

Last Updated : 15 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, all objects are stored in a heap. They are allocated using a new operator. The OutOfMemoryError Exception in Java looks like this: 

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory. No more memory could be made available by the garbage collector.

OutOfMemoryError usually means that you’re doing something wrong, either holding onto objects too long or trying to process too much data at a time. Sometimes, it indicates a problem that’s out of your control, such as a third-party library that caches strings or an application server that doesn’t clean up after deploys. And sometimes, it has nothing to do with objects on the heap.

The java.lang.OutOfMemoryError exception can also be thrown by native library code when a native allocation cannot be satisfied (for example, if swap space is low). Let us understand various cases when the OutOfMemory error might occur.

Symptom or Root cause?

To find the cause, the text of the exception includes a detailed message at the end. Let us examine all the errors. 

Error 1 – Java heap space: 

This error arises due to the applications that make excessive use of finalizers. If a class has a finalize method, objects of that type do not have their space reclaimed at garbage collection time. Instead, after garbage collection, the objects are queued for finalization, which occurs later. 

Implementation: 

  • finalizers are executed by a daemon thread that services the finalization queue.
  • If the finalizer thread cannot keep up with the finalization queue, the Java heap could fill up, and this type of OutOfMemoryError exception would be thrown.
  • The problem can also be as simple as a configuration issue, where the specified heap size (or the default size, if it is not specified) is insufficient for the application.

Java




// Java program to illustrate
// Heap error
  
import java.util.*;
  
public class Heap {
    static List<String> list = new ArrayList<String>();
  
    public static void main(String args[]) throws Exception
    {
        Integer[] array = new Integer[10000 * 10000];
    }
}


Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Heap.main(Heap.java:11)

When you execute the above code above you might expect it to run forever without any problems. As a result, over time, with the leaking code constantly used, the “cached” results end up consuming a lot of Java heap space, and when the leaked memory fills all of the available memory in the heap region and Garbage Collection is not able to clean it, the java.lang.OutOfMemoryError:Java heap space is thrown.

Prevention: Check how to monitor objects for which finalization is pending in Monitor the Objects Pending Finalization.

Error 2 – GC Overhead limit exceeded: 

This error indicates that the garbage collector is running all the time and Java program is making very slow progress. After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile-time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown. 

This exception is typically thrown because the amount of live data barely fits into the Java heap having little free space for new allocations. 

Java




// Java program to illustrate
// GC Overhead limit exceeded
  
import java.util.*;
  
public class Wrapper {
    public static void main(String args[]) throws Exception
    {
        Map m = new HashMap();
        m = System.getProperties();
        Random r = new Random();
        
        while (true) {
            m.put(r.nextInt(), "randomValue");
        }
    }
}


If you run this program with java -Xmx100m -XX:+UseParallelGC Wrapper, then the output will be something like this : 

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
    at java.lang.Integer.valueOf(Integer.java:832)
    at Wrapper.main(error.java:9)

Prevention: Increase the heap size and turn off it with the command line flag -XX:-UseGCOverheadLimit. 

Error 3 – Permgen space is thrown: 

Java memory is separated into different regions. The size of all those regions, including the permgen area, is set during the JVM launch. If you do not set the sizes yourself, platform-specific defaults will be used. 

The java.lang.OutOfMemoryError: PermGen space error indicates that the Permanent Generation’s area in memory is exhausted. 

Java




// Java program to illustrate
// Permgen Space error
  
import javassist.ClassPool;
  
public class Permgen {
    static ClassPool classPool = ClassPool.getDefault();
  
    public static void main(String args[]) throws Exception
    {
        for (int i = 0; i < 1000000000; i++) {
            Class c = classPool.makeClass("com.saket.demo.Permgen" + i).toClass();
            System.out.println(c.getName());
        }
    }
}


In the above sample code, code iterates over a loop and generates classes at run time. Class generation complexity is being taken care of by the Javassist library. 

Running the above code will keep generating new classes and loading their definitions into Permgen space until the space is fully utilized and the java.lang.OutOfMemoryError: Permgen space is thrown. 

Prevention : When the OutOfMemoryError due to PermGen exhaustion is caused during the application launch, the solution is simple. The application just needs more room to load all the classes to the PermGen area, so we need to increase its size. To do so, alter your application launch configuration and add (or increase if present) the -XX:MaxPermSize parameter similar to the following example: 

java -XX:MaxPermSize=512m com.saket.demo.Permgen

Error 4 – Metaspace: 

Java class metadata is allocated in native memory. Suppose metaspace for class metadata is exhausted, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown. 

The amount of metaspace used for class metadata is limited by the parameter MaxMetaSpaceSize, which is specified on the command line. When the amount of native memory needed for a class metadata exceeds MaxMetaSpaceSize, a java.lang.OutOfMemoryError exception with a detail MetaSpace is thrown.

Java




// Java program to illustrate
// Metaspace error
  
import java.util.*;
  
public class Metaspace {
    static javassist.ClassPool cp
        = javassist.ClassPool.getDefault();
  
    public static void main(String args[]) throws Exception
    {
        for (int i = 0; i < 100000; i++) {
            Class c = cp.makeClass(
                            "com.saket.demo.Metaspace" + i)
                          .toClass();
        }
    }
}


This code will keep generating new classes and loading their definitions to Metaspace until the space is fully utilized and the java.lang.OutOfMemoryError: Metaspace is thrown. When launched with -XX:MaxMetaspaceSize=64m then on Mac OS X my Java 1.8.0_05 dies at around 70, 000 classes loaded.

Prevention: If MaxMetaSpaceSize, has been set on the command line, increase its value. MetaSpace is allocated from the same address spaces as the Java heap. Reducing the size of the Java heap will make more space available for MetaSpace. This is only a correct trade-off if there is an excess of free space in the Java heap. 

Error 5 – Requested array size exceeds VM limit: 

This error indicates that the application attempted to allocate an array that is larger than the heap size. For example, if an application attempts to allocate an array of 1024 MB but the maximum heap size is 512 MB then OutOfMemoryError will be thrown with “Requested array size exceeds VM limit”. 

Java




// Java program to illustrate
// Requested array size
// exceeds VM limit error
  
import java.util.*;
  
public class GFG {
    static List<String> list = new ArrayList<String>();
  
    public static void main(String args[]) throws Exception
    {
        Integer[] array = new Integer[10000 * 10000];
    }
}


Output:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at GFG.main(GFG.java:12)

The java.lang.OutOfMemoryError: Requested array size exceeds VM limit can appear as a result of either of the following situations: 

  • Your arrays grow too big and end up having a size between the platform limit and the Integer.MAX_INT
  • You deliberately try to allocate arrays larger than 2^31-1 elements to experiment with the limits.

Error 6 – Request size bytes for a reason. Out of swap space?: 

This apparent exception occurred when an allocation from the native heap failed and the native heap might be close to exhaustion. The error indicates the size (in bytes) of the request that failed and the reason for the memory request. Usually, the reason is the name of the source module reporting the allocation failure, although sometimes it is the actual reason. 

The java.lang.OutOfMemoryError: Out of swap space error is often caused by operating-system-level issues, such as: 

  • The operating system is configured with insufficient swap space.
  • Another process on the system is consuming all memory resources.

Prevention: When this error message is thrown, the VM invokes the fatal error handling mechanism (that is, it generates a deadly error log file, which contains helpful information about the thread, process, and system at the time of the crash). In the case of native heap exhaustion, the heap memory and memory map information in the log can be useful.

Error 7 – reason stack_trace_with_native_method: 

Whenever this error message(reason stack_trace_with_native_method) is thrown then a stack trace is printed in which the top frame is a native method, then this is an indication that a native method has encountered an allocation failure. The difference between this and the previous message is that the allocation failure was detected in a Java Native Interface (JNI) or native method rather than the JVM code. 

Java




// Java program to illustrate
// new native thread error
  
import java.util.*;
  
public class GFG {
    public static void main(String args[]) throws Exception
    {
        while (true) {
            new Thread(new Runnable() {
                public void run()
                {
                    try {
                        Thread.sleep(1000000000);
                    }
                    catch (InterruptedException e) {
                    }
                }
            }).start();
        }
    }
}


The exact native thread limit is platform-dependent. For example, tests Mac OS X reveals that: 64-bit Mac OS X 10.9, Java 1.7.0_45 – JVM dies after #2031 threads have been created

Prevention: Use native utilities of the OS to diagnose the issue further. For more information about tools available for various operating systems, see Native Operating System tools. 



Similar Reads

Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Exception Propagation in Java
Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something
3 min read
Exception Handling with Method Overriding in Java
An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t
6 min read
Java - Exception Handling With Constructors in Inheritance
Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep
7 min read
User-defined Custom Exception in Java
An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating
3 min read
Infinity or Exception in Java when divide by 0?
Consider the following code snippets: public class Geeksforgeeks { public static void main(String[] args) { double p = 1; System.out.println(p/0); } } Output: Infinity public class Geeksforgeeks { public static void main(String[] args) { int p = 1; System.out.println(p/0); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by z
1 min read
Array Index Out Of Bounds Exception in Java
Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This
4 min read
Types of Exception in Java with Examples
Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in excep
8 min read
Different Ways to Print Exception Messages in Java
In Java, there are three methods to print exception information. All of them are present in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object. Methods to Print Exceptions in Java There are three methods to print exception messages in Java. These are: 1. java.
2 min read
Output of Java program | Set 12(Exception Handling)
Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test { public static void main(String[] args) { try { System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); } catch(ArithmeticException e) { System.out.printf("3"); } catch(Exce
3 min read
Null Pointer Exception In Java
NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Reason for Null Pointer ExceptionThese are certain reasons for Null Pointer Exception as mentioned below: Invoking a method from
6 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Exception handling in JSP
Java Server Pages declares 9 implicit objects, the exception object being one of them. It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can only be used in error pages. There are two ways of handling exceptions in JSP. They are: By errorPage and isErrorPage attributes of page directiveBy <error-page>
3 min read
Exception Handling in Apache Kafka
Exception handling is an important aspect of any software system, and Apache Kafka is no exception. In this article, we will discuss the various types of exceptions that can occur in a Kafka system and how to handle them. First, it is important to understand the basic architecture of Kafka. A Kafka system consists of a number of brokers, which are
6 min read
How to Handle the SSL(HTTPs) Certification Path Exception in Android Applications?
If you haven't been stung by the below-mentioned exception when running a Java program created by you on your system that connects to an SSL server (HTTPS), be prepared for a bad experience at some time in your development career. Exception: PKIX path construction failed: sun.security.provider.certpath.SunCertPathBuilder Exception: No valid certifi
4 min read
Servlet - Exception Handling
When a servlet throws an exception, the web container looks for a match with the thrown exception type in web.xml configurations that employ the exception-type element. To define the invocation of servlets in response to particular errors or HTTP status codes, you'd have to utilize the error-page element in web.xml. Exception Handling is the proces
4 min read
Spring MVC - Exception Handling
Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generate
6 min read
JUnit 5 - Expected Exception
In JUnit 5, Exception handling is changed compared to exception handling in JUnit 4. JUnit 5 provides the assertThrows() method for that particular exception thrown during execution of the Testing of an application. This assertThrows is available in org.junit.jupiter.api.Assertions class. Mostly this assertThrows() is used for testing expected exce
3 min read
Exception Handling in Spring Boot
Exception handling in Spring Boot helps to deal with errors and exceptions present in APIs, delivering a robust enterprise application. This article covers various ways in which exceptions can be handled and how to return meaningful error responses to the client in a Spring Boot Project. Here are some key approaches to exception handling in Spring
8 min read
Understanding "static" in "public static void main" in Java
Following points explain what is "static" in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It
3 min read
Understanding Object Cloning in Java with Examples
In this article we discuss the Cloneable interface that indicates that a class has provided a safe clone() method. To understand what cloning means recall what happens when you make a copy of a variable holding an object reference. The original and the copy are references to the same object. This means the original and the copy are mutually depende
4 min read
Understanding and Preventing SQL Injection in Java Applications
In the world of web applications and databases, security is paramount. SQL injection is a common and dangerous vulnerability that can compromise your application's integrity. In this article, we will delve into the fundamentals of SQL injection, understand how it works, and learn how to protect your Java applications from this menacing threat. What
5 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Understanding Classes and Objects in Java
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organized around objects rather t
10 min read
Understanding OOPs and Abstraction using Real World Scenario
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. In this article, we will discuss how this OOP's concept is implemented in real world
4 min read
Understanding RxJava Create and fromCallable Operator
In this article, we will learn about the RxJava Create and fromCallable Operators. We can choose between the required function based on what is required skillset is needed. We frequently make mistakes when utilizing RxJava Operators. Let's get this straight so we don't make a mistake. With examples, we shall study the following operations. Createfr
2 min read
Android Networking Bare Skin - Understanding JPost
If you want to create bottom-to-top networking on Android, it is usually quite complicated. As a result, we rely on third-party libraries. But you'll never know what's beneath it. In this example, I've used the networking java.net package to create a networking framework driven by JPost, a class communication framework. JPost This is a Java / Andro
8 min read
Spring - Understanding Inversion of Control with Example
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML)
4 min read
Understanding Wake Locks in Android 13
You may have come across various instances where you would want to keep the device awake when your app is performing some kind of action or a process so that it doesn't go in the background and ultimately get killed by the Android System. Android 13 also comes with many improvements under the hood like improved App-Hibernation and various other bat
5 min read
Understanding USB Communication in Android Apps
In this article, we are going to see how to interact with USB in Android apps. What things are Required and Also 1 mini Project to Get a Clear Idea of How Things Work When We Need to Interact Android Apps With USB. USB Endpoints and InterfacesEndpoints:Endpoints are the channels through which data is transferred between the USB device and the host
7 min read
Practice Tags :