Understanding OutOfMemoryError ExceptionThe java.lang.OutOfMemoryError means that your program needs more memory than your Java Virtual Machine (JVM) allowed it to use!!! This is a runtime error in Java which occurs when you allocate a new object in your application over a period of time continuously and the Garbage Collector (GC) cannot make space available to accommodate a new object, and the heap cannot be expanded further, which resulted this error.
- Improper configuration (not allocating sufficient memory).
- Application is unintentionally holding references to objects and this prevents the objects from being garbage collected.
- Applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time. If the finalizer thread cannot keep up, with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
- Find the root cause of memory leaks with help of profiling tools like MAT, Visual VM , jconsole etc. Once you find the root cause, You can fix this memory leaks.
- Optimize your code so that it needs less memory, using less big data structures and getting rid of objects that are not any more used at some point in your program.
- Increase the default memory your program is allowed to use using the -Xmx option (for instance for 1024 MB: -Xmx1024m). By default, the values are based on the JRE version and system configuration.
Increasing the heap size is a bad solution, 100% temporary, because you will hit the same issue if you get several parallel requests or when you try to process a bigger file.To avoid these issues, write high performance code:
- Use local variables wherever possible.
- Release those objects which you think shall not be needed further.
- Make sure you select the correct object (ex: Selection between String, StringBuffer and StringBuilder).
- Avoid creation of objects in your loop each time.
- Use a good code system for your program(ex: Using static variables Vs. non static variables).
- Try to use caches.
- Try to move with Multy Threading.
- Reached end of file while parsing
- Unreachable statement error in Java
- Int Cannot Be Dereferenced Error - Java
- How to fix java.lang.classcastexception
- How to fix java.util.NoSuchElementException
- How to fix "illegal start of expression" error
- How to resolve java.net.SocketException: Connection reset
- Non-static variable cannot be referenced from a static context
- Error: Could not find or load main class in Java
- How to resolve java.net.SocketTimeoutException
- How to handle the ArithmeticException in Java?