In this article, we will learn what is OutOfMemoryError in Java, its common causes, examples, and solutions.
What is OutOfMemoryError?
The OutOfMemoryError in Java is not an exception but an error. It's thrown by the JVM when it exhausts allocated memory and cannot allocate more, either because no more memory is available or JVM is restricted by certain constraints.
While there are various reasons for this error, the most common is that the application genuinely consumes all available memory due to data-intensive operations or memory leaks.
Common Causes
Examples
1. Large Array Allocation
In this example, we continuously allocate memory by adding large arrays to a list without ever releasing or reusing that memory.
import java.util.ArrayList;
import java.util.List;
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
List<int[]> list = new ArrayList<>();
// Continuously allocate memory without releasing any
while (true) {
list.add(new int[1_000_000]); // Allocating an array with 1 million integers
}
}
}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.javaguides.net.OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:12)
2. Endless Object Creation
public class EndlessObjectsDemo {
static class Dummy {
double[] arr = new double[1000]; // Just to make it a bit larger
}
public static void main(String[] args) {
while (true) {
new Dummy();
}
}
}
Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
Solutions
Increase the Heap Size: The default heap size might not always be enough. It can be increased using JVM options -Xms and -Xmx. For example, -Xms256m -Xmx1024m sets the initial heap size to 256 MB and the maximum heap size to 1 GB.
Profiling: Use profiling tools like VisualVM, YourKit, or MAT (Memory Analyzer Tool) to detect memory leaks or areas of memory inefficiency.
Code Review: Regularly review code, especially loops and recursions, to ensure that you're not unnecessarily creating objects.
Use Caching: Instead of always creating new objects, consider using object pooling or caching mechanisms.
Opt for Efficient Data Structures: Use appropriate data structures and algorithms. An inefficient data structure can consume way more memory than necessary.
Comments
Post a Comment
Leave Comment