Assignments/Article By Gowsika Yogaraj

Stack Overflow Exception & Memory Error Exception in Java

Student Assignment

Test Cases

Published on Oct 19, 2022

Stack Overflow Exception

It is an error that Java doesn’t allow to catch, for instance, stack running out of space, as it’s one of the most common runtime errors one can encounter. The main cause of the Stack Overflow Error is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop.

When does Stack Overflow Error encounter?

When we invoke a method, a new stack frame is created on the call stack or the thread stack size. This stack frame holds the parameters of the invoked method, mostly the local variables and the return address of the method. The creation of these stack frames will be iterative and will be stopped only when the end of the method invokes is found in the nested methods. In amidst this process, if JVM runs out of space for the new stack frames which are required to be created, it will throw a Stack Overflow Error.

How to fix Stack Overflow Error?

Avoiding repetitive calls:

Try to introduce a proper terminating condition or some condition for the recursive calls to ensure that it terminates.

Increasing the Stack Size:

The second method could be, if you notice that it’s implemented correctly but still, we see an error, then we can avoid that only by increasing the Stack Size to store the required number of recursive calls. This is achieved by changing the settings of the compiler.

Cyclic Relationships between classes:

It is the relationship caused when two different classes instantiate each other inside their constructors. Stack Overflow Error is encountered because the constructor of Class A1 is instantiating Class A2, and the constructor of Class A2 is again instantiating Class A1, and it occurs repeatedly until we see Stack Overflow. This error is mainly due to the bad calling of constructors, that is, calling each other, which is not even required, and it doesn’t hold any significance, so we can just avoid introducing them in the codes.

Memory Error Exception in Java

In Java, all objects are stored in a heap. They are allocated using a new operator.

The Out of Memory Error Exception in Java looks like this:
  • Exception in thread "main" java lang Out of Memory Error: 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.
  • Out of Memory Error 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 Out of Memory Error 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 Out of Memory errors might occur.

Error 1 – Java heap space:

This error arises due to the applications that make excessive use of finalizers. If a class has a finalised 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.
  • 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.
  • We receive the corresponding error Java. lang. Stack Overflow Error by JVM, If the stack memory is filled.
  • Stack memory allocation is considered safer than heap memory allocation because the stored data can only be accessed by the owner thread.
  • Memory allocation and de-allocation are faster as compared to Heap-memory allocation. Stack memory has less storage space as compared to Heap-memory.

Error 2 – GC Overhead limit exceeded:

  • This error indicates that the garbage collector is running all the time and the 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 Out of Memory Error 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.

Error 3 – Permgen space is thrown:

Java memory is separated into different regions. The size of all those regions, including the Permian area, is set during the JVM launch. If you do not set the sizes yourself, platform-specific defaults will be used.
  • The java lang Out of Memory Error: PermGen space error indicates that the Permanent Generation’s area in memory is exhausted.

Error 4 – Meta Space:

  • Java class metadata is allocated in native memory. Suppose meta space for class metadata is exhausted, a java. Lang Out of Memory Error exception with a detail Meta Space is thrown.
  • The amount of meta space used for class metadata is limited by the parameter Max Meta Space Size, which is specified on the command line. When the amount of native memory needed for class metadata exceeds Max Meta Space Size, a java lang Out of Memory Error exception with a detail Meta Space is thrown.

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 an Out of Memory Error will be thrown with “Requested array size exceeds VM limit”.

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 Out of Memory Error: 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.

Error 7 – Reason stack trace with native method:

Whenever this error message (reason stack trace with the 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.

Student Assignment

The views expressed in this document are those of the author and do not necessarily reflect the position of the London School of Emerging Technology. View the detailed policy Disclaimer for Student and Personal Websites

Our Latest Blog

Fundamentals of Scala Programming

Mastering the Fundamentals of Scala Programming: A Complete Guide to Functional Programming

Introduction to Scala Programming Scala programming has gained immense popularity in recent years thanks to...
Read More
Java Programming

Java Basics for Beginners: A Step-by-Step Guide to Mastering Java Programming

Introduction to Java programming Java, a versatile and extensively utilised programming language, is popular among...
Read More
Entity Relationship Diagrams (ERD)

Entity Relationship Diagrams (ERD): A Comprehensive Guide

Introduction to Entity Relationship Diagrams (ERD) Entity Relationship Diagrams (ERD) are powerful tools used in...
Read More