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.
Therefore you pretty much have the following options:
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 OutOfMemoryError, write high performance code:
Use local variables wherever possible.
Release those objects which you think shall not be needed further.
Avoid creation of objects in your loop each time.